从一个表中选择多个行,并计算另一个表的计数

时间:2013-01-14 19:47:53

标签: mysql

我在使用select语句时遇到问题。到目前为止我所拥有的是这个 -

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"

这与我想要的很接近,但桌面上还有另一张名为Desk 2的桌子,它完全无视。事实上,如果有第二台预订,那么它包含了对第一台桌子的计数......

整个表格结构如下:

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);

我需要帮助的是如何正确地构造语句,以便为每个桌面输出单独的行及其相关信息。

1 个答案:

答案 0 :(得分: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