2013-01-14 116 views
0

我在選擇語句時遇到了問題。我到目前爲止是這樣的 -從一個表中選擇多個行,並計數另一個表

SELECT COUNT(booked.desk_id), 
    name, 
    desk.desk_id, 
    phone, 
    fax, 
    dock, 
    pc 
FROM desk, booked 
WHERE desk.desk_id = booked.desk_id 
    AND booking_id >=1 
    AND location = "Cheltenham" 

,輸出

"12" "Desk 1" "1" "1" "0" "0" "1" 

這是接近我想要的東西,但在辦公桌上表中的另一臺名爲臺2,這是完全無視。事實上,如果有是臺2訂票它包括了它是什麼顯示爲臺1計數他們的個性化......

整個表strucutres如下:

table "booked" 
INSERT INTO `booked` (`id`, `booking_id`, `desk_id`, `member_id`, `date_booked`) VALUES 
(246, 1358121601, 1, 1, 'Monday 14th January at 4:40pm'), 
(247, 1358121602, 1, 1, 'Monday 14th January at 4:40pm'), 
(248, 1358121604, 1, 1, 'Monday 14th January at 4:40pm'), 
(249, 1358121603, 1, 1, 'Monday 14th January at 4:40pm'), 
(250, 1358121606, 1, 1, 'Monday 14th January at 4:40pm'), 
(251, 1358121605, 1, 1, 'Monday 14th January at 4:40pm'), 
(252, 1358121607, 2, 1, 'Monday 14th January at 4:40pm'), 
(253, 1358121609, 2, 1, 'Monday 14th January at 4:40pm'), 
(254, 1358121608, 2, 1, 'Monday 14th January at 4:40pm'), 
(255, 1358121610, 2, 1, 'Monday 14th January at 4:40pm'), 
(256, 1358121612, 2, 1, 'Monday 14th January at 4:40pm'), 
(257, 1358121611, 2, 1, 'Monday 14th January at 4:40pm'); 

table "desk" 
INSERT INTO `desk` (`location`, `desk_id`, `name`, `phone`, `fax`, `dock`, `pc`) VALUES 
('Cheltenham', 1, 'Desk 1', 1, 0, 0, 1), 
('Cheltenham', 2, 'Desk 2', 1, 1, 0, 1); 

我需要什麼樣的幫助與如何正確地構造語句,以便它將輸出每個桌子的個別行與它的相關信息。

回答

2

你缺少一個GROUP BY與聚合函數一起去:

SELECT COUNT(booked.desk_id), 
    name, 
    desk.desk_id, 
    phone, 
    fax, 
    dock, 
    pc 
FROM desk 
INNER JOIN booked 
    ON desk.desk_id = booked.desk_id 
WHERE booking_id >=1 
    AND location = "Cheltenham" 
GROUP BY name; 

在MySQL中,你不必GROUP BY在選擇列表中的所有領域,但在其他RDBMS,你將不得不使用:

SELECT COUNT(booked.desk_id), 
    name, 
    desk.desk_id, 
    phone, 
    fax, 
    dock, 
    pc 
FROM desk 
INNER JOIN booked 
    ON desk.desk_id = booked.desk_id 
WHERE booking_id >=1 
    AND location = "Cheltenham" 
GROUP BY name, desk.desk_id, phone, fax, dock, pc 

根據您的樣本數據和評論,你可以使用:

SELECT coalesce(CountDesk, 0) Total, 
    name, 
    d.desk_id, 
    phone, 
    fax, 
    dock, 
    pc 
FROM desk d 
LEFT JOIN 
(
    select COUNT(booked.desk_id) CountDesk, 
    desk_id 
    from booked 
    WHERE booking_id >=1 
    GROUP BY desk_id 
) b 
    ON d.desk_id = b.desk_id 
WHERE location = "Cheltenham" 

SQL Fiddle with Demo

如果你想做到這一點沒有子查詢:

SELECT 
    Coalesce(count(b.desk_id), 0) Total, 
    name, 
    d.desk_id, 
    phone, 
    fax, 
    dock, 
    pc 
FROM desk d 
LEFT JOIN booked b 
    ON d.desk_id = b.desk_id 
WHERE booking_id >=1 
    AND location = "Cheltenham" 
GROUP BY name, d.desk_id, phone, fax, dock, pc ; 

SQL Fiddle with Demo

+0

嗨上面看起來不錯,但如果booked.desk_ids的計數= 0,那麼它不輸出行。我需要它說0如果沒有預訂...任何想法? – Steve

+0

@Steve看我編輯 – Taryn

+0

看起來很美,交配。完美的作品。那是最簡單的方法嗎?瘋狂的長查詢,哈哈。 – Steve

相關問題