简体   繁体   English

从一个表中选择,从另一个表中计数,其中 id 未链接

[英]select from one table, count from another where id is not linked

Table 1表格1

在此处输入图片说明

Table 2表 2

在此处输入图片说明

Expected Output预期产出

Open |打开 | 2 2

Pending |待定 | 0 0

Closed |已关闭 | 0 0

so on....很快....

I tried using this below query我尝试使用以下查询

SELECT d.status , COUNT(*) num,e.name  FROM table1 d  cross join table 2 e group by name;

Which resulted in这导致

在此处输入图片说明

Can any one help me on this.谁可以帮我这个事。

You need a left join .你需要一个左连接 This type of join shows all rows from the left table, even when no rows from the right table exist.这种类型的联接显示左表中的所有行,即使右表中不存在任何行。

select t2.name, count(t1.id)
from table2 as t2
left join table1 as t1 on t2.name = t1.status
group by t2.name

Note you need to aggregate on a column from table1 to produce the 0 desired, hence the count(t1.id) .请注意,您需要聚合table1的列以生成所需的0 ,因此是count(t1.id) count(*) will produce 1 even if there is no row from table1 .即使table1没有行, count(*)也会产生1

A cross join as you have in your query simply creates a Cartesian product of the two tables involved, resulting in every row from the left table joined with every row in the right table once.查询中的交叉联接只是创建所涉及的两个表的笛卡尔积,导致左表中的每一行与右表中的每一行连接一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM