0

当我运行此查询时:

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 子句中取出 dups,我会得到:

tag_id  product_id  dups
2   7038    2
2   1294    1

我想我不能在 where 子句中使用 dups 字段,因为该字段是动态生成的。那么我该怎么做呢?

4

2 回答 2

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
于 2010-09-28T13:44:07.217 回答
1

dups只是count().. 结果的别名。我不确定您是否可以count(m.product_id)=(SELECT ...)WHERE子句中使用,如果不能,我会说您可以在HAVING子句中对其进行测试

于 2010-09-28T13:45:11.957 回答