我有两张桌子 - 活动和与会者。
我正在尝试使用php通过events.id点击与会者列表,并显示由id链接的与会者表中列出的与会者。
包含的字段是events.id和attendees.id,并显示该事件的与会者。
这就是我现在所拥有的。
SELECT events.*, attendees.*
FROM attendees ON event.id = attendees.id
WHERE event.id = attendees.id
答案 0 :(得分: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>
答案 1 :(得分:0)
如果您有两个这样的表:
events:
ID
...
attendees:
event
...
您需要获取与其活动相关的与会者列表,请尝试以下操作:
SELECT * FROM attendees LEFT OUTER JOIN events ON attendees.event = events.ID
如果没有,请澄清你的问题。