簡體   English   中英

SQL-如何選擇列中具有value1但同一列中沒有value2的所有行?

[英]SQL - how to select all rows which have value1 in column but not value2 in same column?

我有一個這樣的SQL表:

------------------------------------------
ID    | SKU      | Name        |  Type
-------------------------------------------
2     | ABC      | Pasta       |  2
3     | XYZ      | Maggi       |  5
2     | ABC      | Pasta       |  5
6     | MNO      | Macroni     |  2
3     | XYZ      | Maggi       |  0
3     | XYZ      | Maggi       |  2

我需要找到類型2但沒有類型5或0的條目的行

例如:它應導致

------------------------------------------
ID    | SKU      | Name        |  Type
-------------------------------------------
6     | MNO      | Macroni     |  2

是否有可能因此只使用一張桌子呢? 當然是的。 該表有140萬行,我使用了此查詢(不確定是否正確)

SELECT e1.* FROM reportmal e1, reportmal e2 
WHERE e1.id= e2.id
AND e1.type=2 AND e2.type=5

該查詢從未返回任何內容,因為它仍在運行。 你能幫我嗎?

我喜歡通過havinggroup by來做到這一點:

select e.id
from reportmal e
group by e.id
having sum(e.type = 2) > 0 and
       sum(e.type in (0, 5)) = 0;

MySQL在數字上下文中將布爾表達式視為整數,其中“ 1”為true,“ 0”為false。 因此, sum(e.type = 2)計算type = 2每個組中的記錄數。 > 0表示至少存在這樣的一行。 = 0表示不存在這樣的行。

如果要原始行,可以將此結果重新join表中。

聽起來像是典型的“不存在”查詢:

select * from atable result
where result.type = 2 and not exists
 (select 1 from atable no50
  where no50.type in (5,0)
        and no50.sku = result.sku
 )

要么:

select * from atable result
where result.type = 2 and result.sku not in
 (select sku from atable no50
  where no50.type in (5,0)
 )

使用group by嘗試使用條件計數查找ID為2而不是0或5的ID,然后使用IN獲取相關行。

select *
from your_table
where id in (
    select
        id
    from your_table t
    group by id
    having count(case when type = 2 then 1 end) > 0
    and count(case when type in (0,5) then 1 end) = 0
);

演示版

select  *
from    reportmal e
where   e.type = 2
    and not exists 
        (
            select  null
            from    reportmal e2
            where   e2.id = e.id
                and e2.type in (0,5)
        ) 

至於性能問題-
您需要的最低要求是報告(id)的索引。
報告編號(id,type)的索引可能更好。

我認為您應該使用此:

SELECT a.*
  FROM reportmal a
 WHERE a.type = 2
   AND NOT EXISTS (SELECT 1
                     FROM reportmal b
                    WHERE b.name = a.name
                      AND b.type IN (5,0));

就像:“所有具有TYPE 2的行,並且不存在具有相同NAME和TYPE 5或0的行”

我不知道您定義“入口”的參數是什么。 也許您應該在子查詢上添加SKU(這完全取決於您的數據模型)。

您的查詢已結束,但您要加入Id,這將為您提供笛卡爾積。

這就是我要做的。

Select p1.*
    From pasta p1
        Left outer join pasta p2 on p1.sku=p2.sku
            And p2.type in (0,5)
        Where p2.type is null

希望對您有幫助。

暫無
暫無

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

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