想要从两个表中选择数据,我需要计算一列并加入

时间:2013-10-18 10:22:14

标签: mysql sql

我有两个数据表,例如表名阻止

|ID | Name |
|1  | B1   |
|2  | B2   |

然后我有另一个名为block_worker的表

|block_id | Name | No Of Worker|
|1        | sam|
|1        | dave|
|2        |  Rob |

现在我想编写一个查询,向我显示来自块表的数据,并根据block worker计算block id表中的worker数。

结果将是这样的

|ID | Name | Worker
|1 | B1 |   2    |
|2 | B2 |   1    |

2 个答案:

答案 0 :(得分:1)

select b.id, b.name, count(w.name) as Workers
from block b
left join block_worker w on w.block_id = b.id
group by b.id, b.name

答案 1 :(得分:1)

Try Like this

    SELECT A.ID,A.Name,COUNT(B.block_id) AS Worker FROM block AS A JOIN block_worker AS B 
ON A.ID = B.block_id GROUP BY B.block_id