1

我有 2 张桌子 - 活动和与会者。

我正在尝试使用 php 在通过 events.id 单击与会者列表并显示由 id 链接的与会者表中列出的与会者。

涉及的字段是 events.id 和 Attendees.id 并显示该事件的与会者。

这就是我目前所拥有的。

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

2 回答 2

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>
于 2012-09-30T22:26:58.387 回答
0

如果你有两个这样的表:

events:  
  ID  
  ...  

attendees:  
  event  
  ...  

您需要获取与他们的活动相关的与会者列表,试试这个:

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

如果不是,请澄清您的问题。

于 2012-09-30T22:30:37.640 回答