2016-09-17 28 views
1

我的查询获取这些产品基于所述结果的查询的次数。我正在尝试对所有存在的实例进行计数,以便按相关性对结果进行排序。我所尝试的一切似乎都会将变量@priority返回为0.任何想法?计数索引存在使用包含多个存在()语句,如果他们在一个单独的表索引中存在

也许是更好地使用加入语句?

谢谢你的帮助。这里是我的MySQL查询:

SELECT `products` . * , @priority 
    FROM `products` 
    LEFT JOIN productstypes_index ON productstypes_index.product_id = products.id 
WHERE (

EXISTS (

SELECT * 
    FROM `productstypes_index` 
    WHERE `productstypes_index`.`product_id` = `products`.`id` 
    AND `productstypes_index`.`_type_id` = '1' 
) 
AND (
(
(

EXISTS (

SELECT @priority := COUNT(*) 
    FROM `producthashtags_index` 
    WHERE `producthashtags_index`.`product_id` = `products`.`id` 
    AND `producthashtags_index`.`producthashtag_id` = '43' 
) 
) 
AND (

EXISTS (

SELECT @priority := COUNT(*) 
    FROM `producthashtags_index` 
    WHERE `producthashtags_index`.`product_id` = `products`.`id` 
    AND `producthashtags_index`.`producthashtag_id` = '11' 
) 
) 
) 
) 
) 
ORDER BY `updated_at` DESC; 
+0

MySQL忽略EXISTS子查询中的SELECT列表,所以它在那里输入的内容没有区别。 –

回答

0

你可以这样做没有那些exists,没有变数。另外,如果连接表上有exists条件,left join就没有意义。那么你不妨做更高效的inner join,并把额外的类型条件放在连接条件中。

优先级可以通过计数在哈希标签来计算,但只有那些与id in ('43', '11')

SELECT  products.* 
      count(distinct producthashtags_index.producthashtag_id) priority 
FROM  products 
INNER JOIN productstypes_index 
     ON productstypes_index.product_id = products.id 
     AND productstypes_index._type_id = '1' 
INNER JOIN producthashtags_index 
     ON producthashtags_index.product_id = products.id 
     AND producthashtags_index.producthashtag_id in ('43', '11') 
GROUP BY products.id 
ORDER BY updated_at DESC; 
+0

我认为你正在做的事情,但我的索引表,producthashtags_index,没有一个ID。 –

+0

嘿trincot,我不需要在这里加入producthashtag_index吗?在“字段列表” –

+0

是的,你做 未知列“producthashtags_index.producthashtag_id”: 我得到一个错误。让我更新一下...... – trincot

0

的MySQL忽略了SELECT列表中是否存在子查询,所以它没有什么区别,你键入那里。这被记录在here

的一种方法使用连接看起来象下面这样:

SELECT p.id, 
     COUNT(case when phi.product_id is not null then 1 end) AS instances 
FROM products p 
INNER JOIN productstypes_index pti ON pti.product_id = p.id AND pti.`_type_id` = 1 
LEFT JOIN producthashtags_index phi ON phi.product_id = p.id AND phi.producthashtag_id IN (11,43) 
GROUP BY p.id 
ORDER BY instances DESC; 

我已删除的附加反引号,我相信他们是不会neccessary并且如果在表中你id列是整数,则不需要引号。

+0

@RickJames感谢您的编辑。复制粘贴别名... :) –

+0

根据其他解决方案,我认为我需要一个唯一的ID为我的索引表。 –

+0

@KevinJ我编辑了答案。试试这个。 –