我有这个问题:
SELECT COUNT( tbl_workstation.workstation_id ) AS AVAILABLE, tbl_lab.room_no,
tbl_lab.capacity
FROM tbl_workstation, tbl_lab
WHERE tbl_workstation.logged_on =0
AND tbl_workstation.startup =1
AND tbl_workstation.lab_name = tbl_lab.lab_name
GROUP BY tbl_lab.lab_name
我得到每个实验室的正确计数 - 但是如果计数为0 - 则不返回任何内容。我还需要返回计数为零的行。我看过做左连接,但是我得到了各种各样的错误。从错误的结果设置到模糊的列错误。怎么了?
答案 0 :(得分:3)
如果您希望获得所有实验室,即使是那些拥有0个工作站的实验室,请使用labs表作为主表,并使用外部联接到工作站表。
这样的事情应该有效:
SELECT COUNT( tbl_workstation.workstation_id ) AS AVAILABLE, tbl_lab.room_no,
tbl_lab.capacity
FROM tbl_lab
LEFT OUTER JOIN tbl_workstation ON tbl_workstation.logged_on =0
AND tbl_workstation.startup =1
AND tbl_workstation.lab_name = tbl_lab.lab_name
GROUP BY tbl_lab.lab_name
答案 1 :(得分:0)
问题在于你的AND tbl_workstation.lab_name = tbl_lab.lab_name
。此查询仅返回实验室中有工作站的结果,这就是您没有从空实验室获得任何结果的原因。
你是对的,你需要使用LEFT JOIN
SELECT COUNT( tbl_workstation.workstation_id ) AS AVAILABLE, tbl_lab.room_no,
tbl_lab.capacity
FROM tbl_workstation
LEFT OUTER JOIN tbl_lab ON bl_workstation.lab_name = tbl_lab.lab_name
WHERE tbl_workstation.logged_on =0
AND tbl_workstation.startup =1
GROUP BY tbl_lab.lab_name
这应该是好的。
答案 2 :(得分:0)
我会建议这样的事情:
SELECT
tbl_lab.lab_name
, tbl_lab.room_no
, tbl_lab.capacity
, SUM (
CASE WHEN tbl_workstation.logged_on = 1 OR tbl_workstation.startup = 0 THEN 0 ELSE 1 END
) as AVAILABLE
FROM tbl_lab, tbl_workstation
WHERE
tbl_workstation.lab_name = tbl_lab.lab_name
GROUP BY tbl_lab.lab_name, tbl_lab.room_no, tbl_lab.capacity
ORDER BY tbl_lab.lab_name, tbl_lab.room_no
我认为tbl_workstation.startup意味着工作站已打开且可用,并且未启动的工作站不可用。即工作站不得登录,必须启动才能使用。