在与一个顶级IT行业的访谈中我被问到这个问题,我完全没有任何线索。谁能告诉我怎么样?无论是Mysql还是Oracle都没问题,但我提供了mysql的例子。
CREATE TABLE employee (employee_ID VARCHAR(5), manager_ID VARCHAR(5));
CREATE TABLE meeting (meeting_ID VARCHAR(1), meeting_title VARCHAR(100));
CREATE TABLE attendee (meeting_ID VARCHAR(1), employee_ID VARCHAR(5));
这个例子的关系非常简单。我认为这是一个非常规范化的例子,直到第3范式。与会者将会议与参与的员工(包括员工和经理)联系在一起。
问题是写一个查询,找出员工和他的经理都参加的会议。
答案 0 :(得分:2)
这样的事情会起作用:
SELECT m.*
FROM meeting m
INNER JOIN attendee a a.meeting_ID = m.meeting_ID
INNER JOIN employee e ON e.employee_ID = a.employee_ID
WHERE (a.meeting_ID,e.manager_ID) IN (SELECT meeting_ID,employee_ID FROM antendee)
或(可能更好)
SELECT m.*
FROM meeting m
INNER JOIN attendee a a.meeting_ID = m.meeting_ID
INNER JOIN employee e ON e.employee_ID = a.employee_ID
INNER JOIN attendee am ON am.employee_ID = e.manager_ID AND am.meeting_ID = a.meeting_ID
答案 1 :(得分:2)
如果您只需要会议名称,可以使用此查询:
SELECT DISTINCT meeting.meeting_title
FROM
attendee a1 INNER JOIN employee e ON a1.employee_ID=e.employee_ID
INNER JOIN attendee a2 ON e.manager_ID=a2.employee_ID
INNER JOIN meeting ON a1.meeting_ID = meeting.meeting_ID
WHERE
a1.meeting_ID=a2.meeting_ID
答案 2 :(得分:0)
试试这个,a和b参加的会议和b是
的经理SELECT m.*
FROM meeting m
JOIN attendee a a.meeting_ID = m.meeting_ID
JOIN attendee b b.meeting_ID = m.meeting_ID AND a.employee_ID <> b.employee_ID
JOIN employee e ON e.employee_ID = a.employee_ID AND e.manager_ID = b.employee_ID