0

我正在寻找编写 MySQL 查询的帮助。

每行至少有两行具有相同的 conversation_id。我想选择在所有行中具有相同会话 ID 的收件人状态字段中具有“删除”的那些。

SELECT conversation_id
FROM xf_conversation_recipient
GROUP BY recipient_state HAVING (delete in all fields)

将选择以下对话 ID

conversation_id recipient_state
1               delete
1               delete

不会选择以下对话 ID

conversation_id recipient_state
1               delete
1               active
4

3 回答 3

2
SELECT conversation_id, COUNT(DISTINCT recipient_state) AS nb, recipient_state
FROM xf_conversation_recipient
GROUP BY conversation_id
HAVING nb=1 AND recipient_state='delete'

查询按对话 ID 分组,仅保留具有 1 个不同收件人状态且收件人状态等于“删除”的记录。

于 2013-04-17T18:00:40.190 回答
0

我能想到的最好的方法是自左加入:

SELECT DISTINCT r1.conversation_id
FROM xf_conversation_recipient AS r1
LEFT JOIN xf_conversation_recipient AS r2 ON r2.conversation_id = r1.conversation_id AND r2.recipient_state != 'delete'
WHERE r1.recipient_state = 'delete' AND r2.conversation_id IS NULL

基本上,抓取所有没有匹配行且没有“删除”作为状态的行。

于 2013-04-17T17:34:59.350 回答
0

给定一个如下所示的表xf_conversation_recipient

+----------------+----------------+
|conversation_id |recipient_state |
+----------------+----------------+
|1               |delete          |
|1               |delete          |
|2               |active          |
|2               |delete          |
|3               |delete          |
|3               |delete          |
|4               |active          |
|4               |delete          |
|5               |active          |
|5               |active          |
|6               |delete          |
|6               |delete          |
+----------------+----------------+

以下查询返回符合您条件的所有对话的 ID

SELECT 
    conversation_id AS selectedId, 
    count(*) AS count    
FROM xf_conversation_recipient   
WHERE recipient_state = "delete" 
GROUP BY conversation_id 
HAVING count>1 

回报:

+-----------+------+
|selectedId |count |
+-----------+------+
|1          |2     |
|3          |2     |
|6          |2     |
+-----------+------+

请注意,根据您的应用程序,您可能希望在此处停止。


嵌套这个查询,我们可以只提取selectedId列,然后再次嵌套它,我们可以将它用作IN查询的条件,如下所示:

SELECT * FROM xf_conversation_recipient 
WHERE xf_conversation_recipient.conversation_id IN (
    SELECT t1.selectedId FROM (
        SELECT 
            conversation_id AS selectedId, 
            count(*) AS count
        FROM xf_conversation_recipient
        WHERE recipient_state = "delete"
        GROUP BY conversation_id
        HAVING count>1
    ) t1  
)

返回:

+----------------+----------------+
|conversation_id |recipient_state |
+----------------+----------------+
|1               |delete          |
|1               |delete          |
|3               |delete          |
|3               |delete          |
|6               |delete          |
|6               |delete          |
+----------------+----------------+
于 2013-04-17T19:38:27.263 回答