从sql中选择带有for语句的2个表

时间:2013-04-15 12:36:06

标签: mysql sql select

我有2个表,想要从中选择数据

table 1 :
id
name

table 2
id
name
table1.id

我想要一个查询来进行此转换:

table1.id
table1.name
count(table2.id)

这很简单,并通过这种方式解决:

SELECT 
c.id as corridor_id,
c.name as corridor_name,
(SELECT COUNT( r.id ) FROM rooms AS r WHERE r.corridorid = c.id ) as room_count
FROM corridors AS c

现在如果我添加另一个这样的表:

table3
id
name
table2.id

并想要这样的查询:

table1.id
table1.name
count(table2.id)
count(table3.id)

idk我怎么能这样做这个查询,但如果有一种方法我会乐意找到它,很多tnx

2 个答案:

答案 0 :(得分:2)

您希望将它们全部加入,然后将它们分组:

SELECT 
   t1.Id,
   t1.Name,
   Count(t2.Id) AS T2Count,
   Count(t3.Id) AS T3Count 
FROM table1 t1
JOIN table2 t2
ON t1.Id = t2.table1_id
JOIN table3 t3
ON t2.id = t3.table2_id
GROUP BY t1.Id, t1.Name

答案 1 :(得分:1)

此处不需要嵌套SELECT语句。您可以通过分组来实现,并避免重复计算,您需要DISTINCT关键字:

SELECT 
    c.id as corridor_id,
    c.name as corridor_name,
    COUNT(DISTINCT r1.id),
    COUNT(DISTINCT r2.id)
FROM 
    corridors c
    JOIN rooms r ON r.corridorid = c.id
    JOIN rooms2 r2 ON r2.corridorid = c.id
GROUP BY c.id

如果您想正确处理缺失值(0个计数),您也可以这样做:

SELECT 
    c.id as corridor_id,
    c.name as corridor_name,
    IFNULL(COUNT(DISTINCT r1.id), 0),
    IFNULL(COUNT(DISTINCT r2.id), 0)
FROM 
    corridors c
    LEFT JOIN rooms r ON r.corridorid = c.id
    LEFT JOIN rooms2 r2 ON r2.corridorid = c.id
GROUP BY c.id