需要知道计数查询的正确语法,以便按ID计算行数

时间:2016-11-20 13:54:38

标签: java mysql spring count

我有两张桌子,我想查询每个品牌的汽车数量,并将此数量插入品牌表中的一列 我尝试了很多查询,但无法做到正确。

第一张表,

enter image description here

第二张表,

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要加入计数和分组

这是一个选择,可以通过brand_name查看计数

select b.brand_name, count(*) 
from table_one a 
inner join table_two b on b.brand_id = a.brand_id 
group by b.brand_name

在table_two中添加了所需的列后(例如使用alter table命令添加my_count_col)

你可以使用像这样的更新

update table_two
inner join (
 select b.brand_name, count(*)  my_count
     from table_one a 
     inner join table_two b on b.brand_id = a.brand_id 
     group by b.brand_name ) t on t.brand_name  = table_two.brand_name
set table_two.my_count_col = t.my_count

答案 1 :(得分:0)

使用$scope

<强>查询

JOIN