我的查询根据它们是否存在于单独的表索引中来获取这些产品的结果。我试图计算它们存在的所有实例,以便我可以按相关性对结果进行排序。我尝试的所有东西似乎都将变量@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 :(得分:0)
MySQL忽略了EXISTS子查询中的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;
我已经删除了其他反引号,我认为它们不是必需的,如果表中的id
列是整数,则不需要引号。
答案 1 :(得分:0)
你可以没有那些exists
,没有变量。另外,如果您在联接表上有left join
条件,则exists
没有任何意义。然后你也可以做更高效的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;