我需要生成如下所述的表格。我有这些样品,但它不起作用。任何请帮助。
SELECT id, room, bed, bed -(SELECT count(bed) FROM tb_student WHERE room_id = id) as FREE FROM tb_rooms tb_rooms +----+-------+-----+ | ID | ROOM | BED | +----+-------+-----+ | 1 | A111 | 4 | | 2 | A112 | 2 | | 3 | A113 | 2 | | 4 | A114 | 2 | +----+-------+-----+ tb_student +----+---------+----------+ | ID | STUD_ID | ROOM_ID | +----+---------+----------+ | 1 | 211 | 3 | | 2 | 212 | 1 | | 3 | 213 | 1 | | 4 | 214 | 2 | +----+----------+---------+ I need something like this... +----+-------+------+-----+ | ID | ROOM | BED |FREE | +----+-------+------+-----+ | 1 | A111 | 4 | 2 | | 2 | A112 | 2 | 1 | | 3 | A113 | 2 | 1 | | 4 | A114 | 2 | 2 | +----+-------+------+-----+
答案 0 :(得分:1)
试试这个
SELECT id as id, room as room, bed as bed,
bed -( SELECT count(Room_ID) FROM tb_student where room_id = soh.id) as FREE
FROM tb_rooms soh
祝你好运
答案 1 :(得分:0)
你好john你的查询权限只创建你的表的别名 看到你的问题:
SELECT id as id, room as room, bed as bed,
bed -( SELECT count(*) FROM tb_student where room_id = tr.id) as FREE
FROM tb_rooms tr
答案 2 :(得分:0)
你可以试试这个:
SELECT
r.ID,
r.ROOM,
r.BED,
r.BED - COUNT(DISTINCT s.ID) AS FREE
FROM tb_rooms AS r
LEFT JOIN tb_student AS s ON r.ID = s.ROOM_ID
GROUP BY r.ID, r.ROOM, r.BED
这是SQLFIDDLE
。