mySQL在给定第三列值的两列中选择出现

时间:2016-01-30 23:53:20

标签: mysql

我有一张这样的表

Sender_id | Receiver_id | Topic
  456     |     123     |   1
  123     |     456     |   3
  123     |     456     |   2
  456     |     123     |   2
  123     |     789     |   1
  123     |     456     |   1
  123     |     789     |   4
  456     |     123     |   1

我想知道每个主题发言者(可以是发送者还是接收者)参与该对话

  

例如。对于主题2,123先生和456先生是唯一的两位发言者

期望的结果是只有值:123,456

Speakers |   Topic
  123    |     2
  456    |     2

这是我的第一次尝试,但我想要合并两个结果列

SELECT * 
FROM (
    SELECT sender_id 
    FROM [table] 
    WHERE topic = '2'
    AND sender_id !=0
    GROUP BY sender_id) a  
INNER JOIN (
    SELECT receiver_id 
    FROM [table]
    WHERE topic = '2'
    AND receiver_id !=0
    GROUP BY receiver_id) b 
ON sender_id

3 个答案:

答案 0 :(得分:1)

您不需要JOIN,需要UNION

SELECT sender_id Speakers
    FROM [table] 
    WHERE topic = '2'
    AND sender_id !=0
UNION
SELECT receiver_id 
    FROM [table] 
    WHERE topic = '2'
    AND receiver_id !=0

您不需要分组删除重复值,因为UNION会为您执行此操作。

答案 1 :(得分:1)

SELECT Sender_id as speakers, Topic from Table1 WHERE Topic ='2'

UNION

SELECT Receiver_id as speakers, Topic FROM Table1 WHERE Topic = '2'

工作小提琴http://sqlfiddle.com/#!9/4cf5e3/2

答案 2 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,Sender_id INT NOT NULL
,Receiver_id INT NOT NULL
,Topic INT NOT NULL
);

INSERT INTO my_table (sender_id,receiver_id,topic) VALUES
(456,123,1),
(123,456,3),
(123,456,2),
(456,123,2),
(123,789,1),
(123,456,1),
(123,789,4),
(456,123,1);

SELECT speaker FROM
(
SELECT sender_id speaker,topic FROM my_table
UNION
SELECT receiver_id,topic FROM my_table
) x
WHERE topic = 2;
+---------+
| speaker |
+---------+
|     123 |
|     456 |
+---------+