簡體   English   中英

查找一個字段的實例,其中另一個字段的對應值(應該是 1-1)具有多個值

[英]Find instances of a field where corresponding values in another, which should be 1-1, have more than one value

我有一個以會話 ID 為鍵的網站會話表。 每個會話應該只有一個來源 - 會話來自哪里。 然而,少數人出現了兩次。 在兩次出現的人中,少數人仍然有不同的來源。

如果我有一張表格:

session_id | source
123456 | apples
abcdef | oranges
654321 | apples
abc123 | pears
def456 | oranges
123456 | pears

每個 id 應該只有一個來源。 然而,id 123456 有蘋果和梨作為來源。 我想編寫一個查詢,返回像 123456 這樣的 id,它們旁邊有多個源。

我怎么能那樣做?

聚合每個會話並計算不同來源的數量:

select session_id, string_agg(distinct source, ',') as sources
from mytable
group by session_id
having count(distinct source) > 1
order by session_id;

您可以采用不同的 session_id 和 source 並獲得大於 1 的 count(*)

select session_id
from (select distinct session_id, source from tbl) a
group by session_id 
having count(*) > 1

having子句很好,但速度非常慢,因為它需要掃描整個表。

擁有適當的索引,嘗試從某個地方開始

select *
from
    your_table as t1 join your_table as t2 on (t1.session_id = t2.session_id and t1.source <> t2.source);

感謝@ThorstenKettner 提醒我exists ,這可能更有效:

select * from your_table as t1
wherte
    exists (
        select 1 from your_table as t2
        where t1.session_id = t2.session_id and t1.source <> t2.source)

暫無
暫無

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

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