簡體   English   中英

MySQL查詢:為此查詢獲取不同的值

[英]MySQL Query: Getting distinct values for this query

我想獲取所有具有item_id = 100 AND item_id = 200的不同user_id。 在這種情況下,正確的結果將是1。但是在這種簡化的情況下,我的SQL查詢的外觀如何? 表:

user_id    item_id
1          100
1          200
3          100

使用條件聚合:

SELECT user_id
FROM yourTable
WHERE item_id IN (100, 200)
GROUP BY user_id
HAVING COUNT(DISTINCT item_id) = 2;

此技巧首先將限制為僅與您感興趣的兩個項目相對應的記錄,然后斷言匹配的用戶具有兩個不同的項目數,這表明他符合條件。

有時邏輯要求以稍微不同的方式執行此操作:

SELECT user_id
FROM yourTable
GROUP BY user_id
HAVING
    SUM(CASE WHEN item_id = 100 THEN 1 ELSE 0 END) > 0 AND
    SUM(CASE WHEN item_id = 200 THEN 1 ELSE 0 END) > 0;

在某些情況下,這種形式可能會更有用,但其作用相同。

    DROP TABLE IF EXISTS T;
    CREATE table t(user_id int,   item_id int);
    insert into t values
    (1     ,     100),
    (1     ,     200),
    (3     ,     100);


    select user_id
    from t 
    where item_id in (100, 200)
    group by user_id having count(distinct item_id) = 2;

+---------+
| user_id |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

您可以使用自我聯接(直觀上更容易理解):

SELECT DISTINCT(t1.user_id) 
FROM table_name AS t1 inner join table_name AS t2 
ON t1.user_id=t2.user_id 
WHERE t1.item_id=100 and t2.item_id=200;

暫無
暫無

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

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