当我运行此查询时:
SELECT m.tag_id, m.product_id, count(m.product_id) as dups
FROM product_tag_map m
INNER JOIN category_tag_map s ON s.tag_id = m.tag_id
INNER JOIN cart_product p ON m.product_id = p.product_id
WHERE m.product_id = p.product_id
AND s.category_id =508
AND s.include =1
AND dups = (SELECT count(s.category_id) as cats FROM category_tag_map s WHERE s.category_id =508)
GROUP BY m.product_id
ORDER BY dups DESC
我收到此错误:
1054 - 'where子句'中的未知列'dups'
如果我从where子句中取出dup,我会得到这个:
tag_id product_id dups
2 7038 2
2 1294 1
我想我不能在where子句中使用dups字段,因为该字段是动态生成的。那么我怎么能做我想做的事呢?
答案 0 :(得分:3)
在过滤聚合时,您需要使用Having
。 MySQL确实允许你在having子句中引用列别名(大多数其他RDBMS都不允许这样做)
SELECT m.tag_id, m.product_id, count(m.product_id) as dups
FROM product_tag_map m
INNER JOIN category_tag_map s ON s.tag_id = m.tag_id
INNER JOIN cart_product p ON m.product_id = p.product_id
WHERE m.product_id = p.product_id
AND s.category_id =508
AND s.include =1
GROUP BY m.product_id
HAVING dups = (SELECT count(s.category_id) as cats FROM category_tag_map s WHERE s.category_id =508)
ORDER BY dups DESC
答案 1 :(得分:1)
dups 只是count()
结果的别名..我不确定您是否可以在 WHERE 中使用count(m.product_id)=(SELECT ...)
条款,如果不是,我会说你可以在 HAVING 条款中测试它