您的加盟語法是隱性和顯性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>