使用IN(SELECT ....)mySQL查询时未返回任何结果

时间:2018-09-28 22:31:48

标签: mysql

对于与获取所有子类别ID有关的先前问题,我使用此查询提取了所有有效category_id的列表。

SELECT categories_id
FROM (SELECT * FROM categories ORDER BY categories_id)
products_sorted, (SELECT @pv := '151') initialisation
WHERE find_in_set(parent_id, @pv)
AND length(@pv := concat(@pv, ',', categories_id))

仅此查询即可正常工作。

然后我做了一个简单的查询,以检查今天是否已将产品添加到数据库中

SELECT * FROM products
WHERE DATE(products_date_added) = DATE(NOW())

难题的最后一步是检查任何返回产品的master_categories_id是否与第一个查询中返回的category_id相匹配。所以我尝试了

SELECT * FROM products 
WHERE DATE(products_date_added) = DATE(NOW())
AND master_categories_id
IN(SELECT categories_id AS master_categories_id
FROM (SELECT * FROM categories ORDER BY categories_id)
products_sorted, (SELECT @pv := '151') initialisation
WHERE find_in_set(parent_id, @pv)
AND length(@pv := concat(@pv, ',', categories_id)))

我没有收到错误,即使我知道某些产品具有另一个查询中存在的master_categories_id,我也只会得到零结果。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该将其编写为联接而不是WHERE ... IN,因为在WHERE子句中反复使用@pv变量时,其重新分配顺序可能是错误的。

SELECT DISTINCT p.* FROM products AS p
JOIN (
    SELECT categories_id AS master_categories_id
    FROM (SELECT * FROM categories ORDER BY categories_id)
    products_sorted, (SELECT @pv := '151') initialisation
    WHERE find_in_set(parent_id, @pv)
    AND length(@pv := concat(@pv, ',', categories_id))
) AS c
ON c.master_categories_id = p.master_categories_id
WHERE DATE(p.products_date_added) = DATE(NOW())

加入子查询应该只执行一次,就像您单独使用查询一样。