2015-08-24 38 views
0

我有2個表:coursesection如圖sqlfiddleMysql的返回重複簡單的條目加入

我需要選擇'starttime' (or null)每門課程的部分。 有些課程沒有「部分」條目。

查詢:

select section.id, section.course, section.section, IFNULL(schedule.starttime, "null") 
from section 
join schedule on schedule.courseid = section.course 
where course = 3 and section.section > 0 

回報有許多重複的條目中有連接表。

id  course section IFNULL(schedule.starttime, "null") 
7  3  1  1440021600 
7  3  1  1440021620 
7  3  1  1440021640 
8  3  2  1440021600 
8  3  2  1440021620 
8  3  2  1440021640 
9  3  3  1440021600 
9  3  3  1440021620 
9  3  3  1440021640 

當我想到:

id  course section IFNULL(schedule.starttime, "null") 
7  3  1  1440021600 
8  3  2  1440021620 
9  3  3  1440021640 
10  3  4  null 
11  3  5  null 

我試過的DISTINCTGROUP BY不同的組合沒有成功。

+0

他們是不是真的distnct ..是什麼人?日期不同。 – DarkKnight

+0

當你有多個日期時,你如何選擇單一日期?什麼是邏輯? – DarkKnight

+0

@DarkKnight:因爲它給出了與上述完全相同的結果。 http://sqlfiddle.com/#!9/d3f671/7 – gyc

回答

1

可以使用left join然後使用schedule.sectionidsection.id

select section.id, section.course, section.section, IFNULL(schedule.starttime, "") 
from section 
LEFT JOIN schedule ON schedule.sectionid = section.id 
where course = 3 and section.section > 0; 

SEE DEMO

+0

這可以按預期工作,並且連接比Teve的答案「更清潔」。我需要弄清楚爲什麼兩個查詢都有效。 – gyc

+1

@gyc,teve答案的唯一區別是他添加了這樣一個條件'schedule.courseid = section.course',其中它只是多餘的,因爲它已經有一個包含特定值的'course id'的過濾器 –

2

嘗試:

SELECT section.id, section.course, section.section, IFNULL(schedule.starttime, "null") 
FROM section 
LEFT JOIN schedule ON schedule.courseid = section.course AND schedule.id = section.section 
WHERE course = 3 AND section.section > 0 
+0

嗯,它確實返回我想要的,但我不明白爲什麼或者它是否是正確的方式來做到這一點。我從來不需要這樣做。 – gyc

+0

'left join'顯示那些在'section'表中沒有匹配的記錄; 'schedule.id = section.section'的額外條件是選擇適當的'schedule.starttime'值(正如我從源頭看到的那樣) – Teve