2016-06-22 26 views
0

我有以下结构的与会者表找到匹配:如何连接表,包括行,不使用非外键字段

+--------------+---------+ 
| attendee_id | others1 | 
+--------------+---------+ 
| abcd  | B  | 
| ghij  | A  | 
| defg  | C  | 
+--------------+---------+ 

而且还与以下结构的eventattendees表:

+--------------+---------+----------+ 
| attendee_id | others2 | event_id | 
+--------------+---------+----------+ 
| wxyz  | D  |  1 | 
| mlno  | E  |  2 | 
| defg  | F  |  3 | 
+--------------+---------+----------+ 

我想要的是创建一个查询,给出了一些事项标识,返回一个连接这些表(由attendee_id),而且还返回与没有找到匹配的IDS attenddes参加者表信息的行为那event_id。说,对于event_id 3:

+--------------+---------+---------+----------+ 
| attendee_id | others1 | others2 | event_id | 
+--------------+---------+--------------------+ 
| abcd  | A  | null | null | 
| ghij  | B  | null | null | 
| defg  | C  | F |  3 | 
+--------------+---------+--------------------+ 

我该怎么做mysql?

+1

这可以与外部进行连接。 –

+0

我刚才给你提供了以前的数据答案后,你刚刚改变了问题 – Drew

+0

使用更新的答案。我现在得走了。如果您愿意,您可以按任意栏目进行订购。 – Mojtaba

回答

1

使用左连接。第一个表应该是您的主表,第二个表在没有找到匹配的情况下返回null。

SELECT a.*, b.others2, b.event_id FROM attendees a LEFT JOIN eventattendees b ON a.attendee_id = b.attendee_id GROUP BY a.attendee_id 

测试:

CREATE TABLE attendees 
    (`attendee_id` varchar(10), `others1` varchar(10)); 

CREATE TABLE eventattendees 
    (`attendee_id` varchar(10), `others2` varchar(10), `event_id` int); 

INSERT INTO attendees 
VALUES 
    ('abcd', 'B'), 
    ('ghij', 'A'), 
    ('defg', 'C'); 

INSERT INTO eventattendees 
VALUES 
    ('wxyz', 'D', 1), 
    ('mlno', 'E', 2), 
    ('defg', 'F', 3); 


SELECT a.*, b.others2, b.event_id FROM attendees a LEFT JOIN eventattendees b ON a.attendee_id = b.attendee_id GROUP BY a.attendee_id 
+0

但是,这将包括所有事件ID,我只想要事件ID = 3. –

+0

它应该只包括event_id 3.您提供了正确的数据吗? – Mojtaba

+0

为什么要这样?你的回答不包括event_id的条款,也许你编辑它,并提交时出现问题? –

相关问题