SQL-替换HAVING COUNT*== 0

问题描述

因此,我必须进行查询以返回所有不包含“ 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无效,因为没有什么可计数的。

有什么建议吗?

解决方法

您的方法是正确的:-)

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;
,

您可以使用not exists

SELECT reciepts.recieptNumber
FROM reciepts JOIN products
ON reciepts.productCode = products.productCode
where not exist 
  (select 1 from products p where products.productcode=p.productcode 
          and p.productName='Apple')

您可以尝试替代方法-

SELECT reciepts.recieptNumber
    FROM reciepts JOIN products
    ON reciepts.productCode = products.productCode
group by reciepts.recieptNumber
having max(productName)<>'Apple' and min(productName)<>'Apple'
,

从当前查询开始,您可以在having子句中使用条件计数:

SELECT r.recieptNumber
FROM reciepts r 
INNER JOIN products p ON r.productCode = p.productCode
GROUP BY r.recieptNumber
HAVING MAX(p.productName = 'Apples') = 0;

旁注:

  • =用于相等条件而不是==

  • 在字符串中使用单引号-在标准SQL中,双引号表示标识符(例如列或表名)-尽管某些数据库的实现方式有所不同

  • 表别名使查询更易于编写和读取

,

您可以获得苹果的所有收据,然后使用LEFT JOIN

排除它们
SELECT reciepts.recieptNumber
FROM reciepts r
LEFT JOIN (
  SELECT reciepts.recieptNumber
  FROM reciepts JOIN products
  ON reciepts.productCode == products.productCode
  WHERE products.productName == "Apples"
) r_apples
ON r.recieptNumber = r_apples.recieptNumber
WHERE r_apples.recieptNumber IS NULL
,

请尝试以下解决方案:

SELECT DISTINCT reciepts.reciepts.recieptNumber FROM reciepts 
WHERE  reciepts.productCode not in(
 select DISTINCT products.productCode from products where products.productName = 'Apples')

第二种方法是:

SELECT reciepts.reciepts.recieptNumber,sum(case when products.productName = 'Apples' then 1 else 0 end) as total_apple FROM reciepts 
LEFT OUTER JOIN products on reciepts.productCode =  products.productCode 
GROUP BY  reciepts.reciepts.recieptNumber
HAVING total_apple = 0