1

可以说我有 2 张表 Master 和 slave 。Master 表包含 master_name 和 master_id,Slave 表包含 Slave_id、slave_name 和 master_id。

样本数据。

master_id Master_name  Master_status      slave_id  slave_name  master_id status
1         x               online              1          a          1       online
2         y               online              2          b          1       online
3         z               offline             3          c          2       offline
                                              4          d          3       offline
                                              5          e          3       online

我试图获得的预期结果是,

master_id  no_of_slave
   1             2
   2             0

我想知道每个在线主人拥有的在线奴隶的数量。

抱歉编辑晚了。

4

7 回答 7

5

LEFT JOIN像这样使用:

SELECT m.master_id
     , count(s.slave_id) AS no_of_slave
FROM master m 
LEFT JOIN slave s 
     ON m.master_id = s.master_id
GROUP BY m.master_id;

结果:

╔═══════════╦═════════════╗
║ MASTER_ID ║ NO_OF_SLAVE ║
╠═══════════╬═════════════╣
║         1 ║           2 ║
║         2 ║           1 ║
║         3 ║           2 ║
╚═══════════╩═════════════╝

看到这个 SQLFiddle

于 2013-05-29T11:25:59.520 回答
1

使用以下查询:

Select m.master_id, count(s.master_id) as no_of_slave 
       FROM master m 
            JOIN slave s 
            ON m.master_id = s.master_id
            GROUP By m.master_id;
于 2013-05-29T11:27:17.397 回答
0
select 
    a.master_id,
    count(b.slave_id) 
from 
    master a,
    slave b 
where 
     a.master_id=b.master_id 
group by 
     a.master_id
于 2013-05-29T11:26:09.297 回答
0
select    master_id, count(1)
from      Slave
group by  master_id
order by  master_id

只会给你有奴隶的主人,如果表很大,你甚至不需要加入主人

于 2013-05-29T11:26:48.980 回答
0

你可以使用这个。这将起作用。

select m.master_id,(select count(*) from slave s where s.master_id = m.master_id) as no_of_slave from master m
于 2013-05-29T11:28:39.427 回答
0
  SELECT master_id, count(*) AS no_of_slave
    FROM slave
GROUP BY master_id
ORDER BY master_id;
于 2013-05-29T11:29:27.703 回答
0

您对主名称不感兴趣,因此不需要加入,您在从表中拥有所有必要的信息:

select master_id, count(slave_id) as no_of_slave
from Slave
group by master_id
order by master_id --remove this line, if ordering of master ids is not important
;

如果给定的主 ID 不在此结果中,则意味着它没有从属。

于 2013-05-29T11:38:22.697 回答