选择* FROM表2并计算(coulmn_name)FROM表1

时间:2016-07-25 11:21:54

标签: mysql sql database select mysqli

如何选择* FROM表2并计数(t_type)FROM表1表1和表2中的物种相等

表一=树

id | t_type
~~~~~~~~~~~~
1  | Tree one 
2  | Tree two
3  | Tree Three 
4  | Tree Four 
5  | Tree one 

表二=请求

id | req_species
~~~~~~~~~~~~
1  | Tree one 
2  | Tree two 
3  | Tree one 
4  | Tree two 

返回的表将具有与表2(请求)相同的行数,在本例中为4行。

预期产出

species | Qunatity
~~~~~~~~~~~~
Tree one | 2
Tree two | 1
Tree one | 2
Tree two | 1

2 个答案:

答案 0 :(得分:0)

一种方法使用相关子查询:

select r.species,
       (select count(*) from trees t where t.species = r.species) as quantity
from requests r;

答案 1 :(得分:0)

SELECT COUNT(T1.t_type) AS QUALITY,T1.t_type
FROM TABLE_1 AS T1  WHERE T1.t_type IN 
     (SELECT T2.req_species FROM TABLE_2 AS T2)

GROUP BY T1.t_type