mysql - 选择 *FROM 表二并从表一计数(column_name)

标签 mysql sql

如何从表二中选择*并从表一中选择计数(t_type),其中表一和表二中的物种相等

表一 = 树

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 

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

预期输出

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

最佳答案

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

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

关于mysql - 选择 *FROM 表二并从表一计数(column_name),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38566427/

相关文章:

PHP mysql_num_rows() 在 INNER JOIN 查询中的用法

c# - 使用 SqlCommand 参数时调用 SQL 函数要慢得多

sql - 如何按每个日期的金额过滤记录?

php - 关闭ajax调用的连接

mysql - 使用存储过程作为子查询

python - 防止 MySQL-Python 在数据库名称参数周围插入引号

Mysql 内连接多个

mysql - 保留最后 30 个值并删除其余的

mysql - 如何在 Unix 上执行存储过程 SQL (MySQL)

mysql - 选择 * WHERE status <> 'deleted' 或 status <> 'completed' AND update_datetime < unix_timestamp(now() - 间隔 7 天)