2016-06-22 25 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的條款,也許你編輯它,並提交時出現問題? –

相關問題