我的表只包含两列ID和product,如下所示:
ID Product
-----------------
1 microsoft
0 cisco
2 cisco
7 cisco
3 vmware
0 adobe
0 microsoft我需要编写一个仅列出具有id=0的记录的查询,
ID Product
---------------
0 adobe 我不想列出的原因
ID Product
----------------
0 micrsoft
0 cisco 是因为他们有一个或多个具有产品ID的记录。
我试过了:
SELECT
[ProductID], [Product]
FROM [table] AS t1
WHERE ProductID = 0
AND NOT EXISTS (SELECT 1
FROM [table] AS t2
WHERE t1.ProductID = t2.ProductID
AND t2.ProductID <> 0)似乎要花很长时间来查询。(表有2,000,000条记录)
发布于 2015-07-21 01:17:01
使用带有having子句的简单group by:
select 0 as id, product
from [table] t
group by product
having min(id) = 0 and max(id) = 0;发布于 2015-07-21 01:09:23
你只需要在产品上加入,而不是在ProductID上:
SELECT [ProductID],[Product]
FROM [table] as t1
where ProductID=0
AND NOT EXISTS (
SELECT 1 FROM [table] AS t2
where t1.Product=t2.Product
AND t2.ProductID<>0
)这将转换为“其中不存在产品具有相同名称且ID不为0的其他行”。
https://stackoverflow.com/questions/31522250
复制相似问题