簡體   English   中英

SQL 查詢以查找一組行,這些行在其中一個字段中都具有特定值

[英]SQL Query to find a group of rows having all of them a certain value in one of its fields

給定表:

+---+-------+------+---+
|id | attr  | fker |did|
+---+-------+------+---+
|1  | attr1 | 5    |  1|
|2  | attr1 | 17   |  1|
|3  | attr1 | 3    |  2|
|4  | attr2 | 31   |  2|
|5  | attr2 | 7    |  2|
|6  | attr2 | 6    |  2|
|7  | attr3 | NULL |  1|
|8  | attr3 | NULL |  2|
|9  | attr3 | NULL |  1|
|10 | attr4 | NULL |  1|
|11 | attr4 | NULL |  1|
|12 | attr4 | NULL |  1|
+---+-------+------+---+

我需要一個 SQL 查詢,該查詢將列出所有且僅具有fker=NULL所有 did=1 的 attr

在這個例子中,

  • 只有 attr4 滿足這個條件,因為
  • attr1 沒有 fker=NULL,
  • attr2 沒有它的所有 did=1 (實際上沒有),
  • attr3 沒有它的所有 fekr=NULL(即使它有,它也有=2)。

換句話說,查詢的結果集中應該只有“attr4”。

http://sqlfiddle.com上使用以下示例:

CREATE TABLE IF NOT EXISTS `ha_example` (
  `id` int(6) unsigned NOT NULL,
  `attr` varchar(200) NOT NULL,
  `fker` int null,
  `did` int(3) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `ha_example` (`id`, `attr`, `fker`, `did`) VALUES
    ('1',  'attr1',  '5',     '1'),
    ('2',  'attr1',  '17',    '1'),
    ('3',  'attr1',  '3',     '2'),
    ('4',  'attr2',  '31',    '2'),
    ('5',  'attr2',  '7',     '2'),
    ('6',  'attr2',  '6',     '2'),
    ('7',  'attr3',  NULL,  '1'),
    ('8',  'attr3',  NULL,  '2'),
    ('9',  'attr3',  NULL,  '1'),
    ('10', 'attr4',  NULL,  '1'),
    ('11', 'attr4',  NULL,  '1'),
    ('12', 'attr4',  NULL,  '1');

我試過這個 SQL (在這里類似問題的幫助下——相似但不相同):

SELECT COUNT(fker), SUM(CASE WHEN did = 1 THEN 1 ELSE 0 END), attr,  he.*
FROM ha_example he
group by attr,did
HAVING COUNT(fker) = SUM(CASE WHEN did = 1 THEN 1 ELSE 0 END)

但是我無法得出attr的所有行的 TOTAL 計數,而不是放棄兩個字段而不是一個字段的組。

我該如何做到這一點?

您可以使用group byhaving

select attr
from ha_example he
gropu by attr
having count(fker) = 0 and max(did) = min(did) and max(did) = 1;

您還可以使用:

having sum( fker is not null or did <> 1 ) = 0

或者,如果您願意:

having sum( not (fker is null and did = 1) ) = 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM