2013-03-05 43 views
0

我在我的數據庫中產生期望的結果時遇到問題。我想從其他表中提取「總行數」,其中條件將屬於另一個表。要說清楚,下面是示例插圖。在我的方案中需要的正確SQL語句

>tblBus 
> 
>Bus ID ~ Day~ Type 
> 
>1000 | Monday | Public 

>2000|Monday | Private 

>3000|Tuesday| Public 

>4000|Monday | Public 


>tblReservation 
> 
>Bus ID | Date 

>1000 | 2013/3/4 

>2000 | 2013/3/4 

>3000 | 2013/3/6 

讓說,預訂當天是星期一,這是2013年3月4日..我想顯示所有的公共巴士上可用的週一新行有保留的總數在那輛巴士上製造的。

例如

GeneratedTable(其中date = '2013/3/4',類型= '公共',天= '星期一')

>Bus ID | Day | Type | TotalNumberReservation 

>1000 |Monday | Public | 1 

>4000 |Monday | Public | 1 
+0

'JOIN','GROUP BY'和'COUNT'。 – Wrikken 2013-03-05 19:21:19

回答

1

你可以用它連接在bus id,然後你的表如下得到保留的計數:

select b.`bus id`, 
    b.day, 
    b.type, 
    count(r.date) TotalNumberReservation 
from tblBus b 
inner join tblReservation r 
    on b.`bus id` = r.`bus id` 
where r.date = '2013-03-04' 
    and b.day = 'Monday' 
group by b.`bus id`, b.day, b.type 

SQL Fiddle with Demo

如果要返回匹配正確的一天,所有的行,即使沒有預約,然後喲U將要使用LEFT JOIN

select b.`bus id`, 
    b.day, 
    b.type, 
    count(r.date) TotalNumberReservation 
from tblBus b 
left join tblReservation r 
    on b.`bus id` = r.`bus id` 
    AND r.date = '2013-03-04' 
where b.day = 'Monday' 
group by b.`bus id`, b.day, b.type 

SQL Fiddle with Demo

+0

已編輯:它有一個問題,它應該仍然顯示所有同一天的巴士。例如在週一的所有巴士 – ChaosDarky 2013-03-05 19:38:56

+0

@DandeloDarkyCardona看到我的編輯,您將需要使用'LEFT JOIN'而不是 – Taryn 2013-03-05 19:41:43

+0

我已經在我的系統上嘗試過它,它的工作完美無瑕!謝謝! :D直到下一次^ _ ^你是如此的親! – ChaosDarky 2013-03-05 19:55:30

0

這裏是產生所有總線,天,日期計數,然後就可以過濾你所需要的基本查詢:

Select a.bus_id, day, type, count(*) as TotalNumberReservation 
    from tblBus a 
    join tblReservation b 
    on a.busId=b.busId 
group by a.bus_id,day,type