我想过滤掉小于3的结果,但每当我添加WHERE语句时,查询都会失败。我的查询有什么问题?我正在使用MySQL Workbench 3.7
SELECT c.name, COUNT(DISTINCT s.product_id) AS veggies
FROM sales AS s
INNER JOIN customers AS c
ON c.id=s.customer_id
GROUP BY s.customer_id
WHERE veggies > 2"
谢谢! 约尼
答案 0 :(得分:2)
where
应为having
:
SELECT c.name, COUNT(DISTINCT s.product_id) AS veggies
FROM sales s INNER JOIN
customers c
ON c.id = s.customer_id
GROUP BY s.customer_id
HAVING veggies > 2;
您的查询生成语法错误(即未运行)或在GROUP BY
停止并忽略WHERE
。
答案 1 :(得分:-1)
需要在HAVING
之后使用GROUP BY
而不是WHERE
:
SELECT
c.name, COUNT(DISTINCT s.product_id) AS veggies
FROM
sales AS s
INNER JOIN customers AS c ON c.id = s.customer_id
GROUP BY
s.customer_id
HAVING
veggies > 2
答案 2 :(得分:-1)
Grouping requires knowledge of entire list. There is an order of operations in mysql query。 (点击此链接将显示回答该页面的页面)
这很有希望,
SELECT c.name, COUNT(DISTINCT s.product_id) AS veggies'
FROM sales AS s
INNER JOIN customers AS c
ON c.id=s.customer_id
WHERE veggies > "2"
GROUP BY s.customer_id
交换这两行。
GROUP BY s.customer_id
WHERE veggies > "2"
GROUP BY始终位于WHERE之后。
除此之外,你在这里错过了2左右的开场报价。
WHERE veggies > 2"
在第一行末尾有一个不必要的单引号(')。