2016-11-20 77 views
-1

我得到了这两个表,我想有一个查询来计算每个品牌的汽车数量,并将此计数插入到品牌表中的一列 我已经尝试了很多查询,但不能正确地做。需要知道一个计数查询的正确语法来计数行ID

第一个表,

enter image description here

二表,

enter image description here

+0

你是一个SQL答案或JPA回答后? –

+0

我正在使用百里香,并且想要制作一个按品牌排列的汽车数量的图表。所以即时寻找一个SQL答案 – tijn167

回答

0

使用JOIN列。

查询

select t1.car_brand_id, t2.brand_name, count(t1.car_name) as total_count 
from table1 t1 
join table2 t2 
on t1.car_brand_id = t2.brand_id 
group by t1.car_brand_id, t2.brand_name; 
+0

谢谢这工作对我:) – tijn167

+0

@ tijn167:请标记为答案。 – Wanderer

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 
相关问题