2012-09-30 45 views
1

我有2個表格 - 活動和與會者。使用Id從鏈接表中顯示MySql數據

我正在嘗試使用php在通過events.id單擊與會者列表時顯示與id鏈接的與會者表中列出的與會者。

envolved字段包括events.id和attendees.id,並顯示該事件的與會者。

這是我目前所擁有的。

SELECT events.*, attendees.* 
FROM attendees ON event.id = attendees.id 
WHERE event.id = attendees.id 

回答

1

您的加盟語法是隱性和顯性JOIN語法不正確的搭配,缺少JOIN關鍵字,而是複製WHERE子句中的連接條件。

SELECT 
    events.*, 
    attendees.* 
FROM 
    attendees 
    JOIN events ON event.id = attendees.id 
WHERE 
    event.id = <event to find attendees for> 

需要注意的是不可取在PHP中使用events.*, attendees.*,因爲你將有一個無法訪問到PHP重複的列名。取而代之的,是明確的:

SELECT 
    /* Be explicit about the columns you select in a JOIN query */ 
    events.id AS event_id, 
    events.name AS event_name, 
    events.someothercol, 
    attendees.id AS attendee_id, 
    attendees.name AS attendee_name 
FROM 
    attendees 
    JOIN events ON event.id = attendees.id 
WHERE 
    event.id = <event to find attendees for> 

如果您仍然希望得到該事件的細節,即使它沒有參加,使用LEFT JOIN代替:

SELECT 
    /* Be explicit about the columns you select in a JOIN query */ 
    events.id AS event_id, 
    events.name AS event_name, 
    events.someothercol, 
    attendees.id AS attendee_id, 
    attendees.name AS attendee_name 
FROM 
    events 
    /* LEFT JOIN will return event details even when there are no attendees */ 
    LEFT JOIN attendees ON event.id = attendees.id 
WHERE 
    event.id = <event to find attendees for> 
0

如果你有兩個表是這樣的:

events: 
    ID 
    ... 

attendees: 
    event 
    ... 

而且你需要得到他們的事件相關聯的與會者名單,試試這個:

SELECT * FROM attendees LEFT OUTER JOIN events ON attendees.event = events.ID 

如果不是,請說明您的問題。

相關問題