mysql - SQL - 替换 HAVING COUNT(*) == 0

标签 mysql sql join count having-clause

所以我必须进行查询以返回所有不包含“apple”项目的收据号。

数据如下。 EG 如果您去商店购买苹果和香蕉,数据将是:

(table reciepts)
recieptNumber      productCode
12345              9999
12345              8888

(table products)
productCode        productName
9999               Apples
8888               Bananas

我在想:

SELECT reciepts.recieptNumber
FROM reciepts JOIN products
ON reciepts.productCode == products.productCode
WHERE products.productName == "Apples"
GROUP BY reciepts.recieptNumber
HAVING COUNT(*) == 0;

但我现在知道,在 count = 0 时,having 不起作用,因为没有什么可计算的。

有什么建议吗?

最佳答案

你的方法是在正确的轨道上:-)

SELECT reciepts.recieptNumber
FROM reciepts 
-- switch to Outer Join
LEFT JOIN products
ON reciepts.productCode = products.productCode
-- this will result in a NULL row when there's no Apple in the receipt
-- otherwise a row with 'Apples'
AND products.productName = 'Apples' 
GROUP BY reciepts.recieptNumber
-- if there's only a NULL you found the matching receipt 
HAVING COUNT(products.productCode) = 0;

关于mysql - SQL - 替换 HAVING COUNT(*) == 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63842965/

相关文章:

java - Hibernate 连接两个表

mysql - 需要提高sql性能

php - Blue-imp file-upload 从带有附加变量的数据库中删除

php - Ubuntu 12.04 php、mysql-server 和 phpmyadmin 安装 apache2 Web 服务器错误

php - 不应该使用公开的自动递增 PK 吗?

php - SQL 查询没有被执行

java - 聊天服务器 : what's the best(optimized) way to save a conversation log

mysql - 如何根据评分获得前3名用户

c# - 显式类型转换的好处?

t-sql - 将5个表数据合并到主表中