2010-08-15 57 views
0

我有以下表格:SQL連接查詢不作爲想

CREATE TABLE `attendance_event_attendance` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`talk_id` varchar(200) NOT NULL, 
`membersAttended_id` varchar(200) NOT NULL, 
PRIMARY KEY (`id`), 
KEY `attendance_event_attendance_9ace4e5a` (`talk_id`), 
KEY `attendance_event_attendance_3c0dadb7` (`membersAttended_id`) 
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; 

CREATE TABLE `attendance_member` (
`name` varchar(200) NOT NULL, 
`telephone_number` varchar(200) NOT NULL, 
`email_address` varchar(200) NOT NULL, 
`membership_type` varchar(1) NOT NULL, 
`membership_number` varchar(200) NOT NULL, 
PRIMARY KEY (`membership_number`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

CREATE TABLE `attendance_talk` (
`title` varchar(200) NOT NULL, 
`speaker` varchar(200) NOT NULL, 
`date_of_talk` date NOT NULL, 
PRIMARY KEY (`title`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

我想選擇所有沒有參加最近兩次會談的成員。我寫的查詢看起來是這樣的:

SELECT m.name 
    from attendance_member as m 
left outer join attendance_event_attendance as ea on (ea.membersAttended_id=m.membership_number) 
join attendance_talk as t on (ea.talk_id = t.title) 
where t.date_of_talk >= 2010-06-01 
    AND ea.membersAttended_id = null; 

這是正確的嗎?或者我沒有正確理解連接?
由於事先
院長

回答

1

一個有點可怕的做法,我擔心 - 而是一個應該工作...

SELECT m.name 
from attendance_member as m 
left outer join (
SELECT ea.membersAttended_id 
FROM attendance_event_attendance as ea 
join attendance_talk as t on (ea.talk_id = t.title) 
where t.date_of_talk >= 2010-06-01 
GROUP BY ea.membersAttended_id 
HAVING COUNT(*) = 2 
) attendingmembers 
ON attendingmembers.membersAttended_id = m.membership_number 
WHERE attendingmembers.membersAttended_id IS NULL 
+0

謝謝。我想我真的需要在我的SQL上工作......因爲我正在做更多的數據庫工作。 – Dean 2010-08-15 21:11:51

+0

@Dean - 以上是相當噁心的 - 日期+ HAVING COUNT(*)= 2是可怕的,有更好的方法,引入另一個子查詢來獲得'最近的兩次會談'會比date_of_talk>某個日期好得多。 – 2010-08-15 21:15:19

1

差不多完全一樣,你會說英語

Select Distinct m.name   -- Select names 
    From attendance_member M  -- of members 
     Where Not Exists   -- who did not attend the last two talks 
     (Select * From attendance_event_attendance a 
      Join attendance_talk t 
       On a.talk_id = t.title 
     Where a.membersAttended_id = m.membership_number 
      And (Select Count(*) From attendance_talk 
       Where date_of_talk >= t. date_of_talk) <= 2) 

注:子查詢:

(Select * From attendance_event_attendance a 
    Join attendance_talk t 
     On a.talk_id = t.title 
    Where a.membersAttended_id = m.membership_number -- (correlated w/outer query) 
    And (Select Count(*) From attendance_talk 
      Where date_of_talk >= t. date_of_talk) <= 2) 

返回參加會談的會員名單,後續會談的會話數爲2或更少