SQL:如何在SELECT查询结果中添加列? [英] SQL: How to add a column in the SELECT query result?
问题描述
通常,我们将在SQL查询中选择字段.例如
Usually we will select the field(s) in the SQL query. e.g.
SELECT A.id FROM Member A
但是,如果我要对齐元素与另一个所选字段相对应的列,该怎么办? 例如,我想从成员表中选择成员ID,然后选择COUNT,该计数计算成员在其他表的元组中出现的次数
But what if I want to align a column which elements correspond to the other selected field? For example I want to select the member ID from a member table, and the COUNT that count how many times the member appear in the tuple of other table
那么如何使COUNT列与选择结果对齐?
So how do I make the COUNT column that align together with the select result?
推荐答案
如果我对您的理解正确,这就是你想要的:
If I understood you correctly, this is what you want:
SELECT A.id, count(B.MemberID)
FROM Member A
LEFT JOIN TableB B on A.id = B.MemberID
group by A.id
LEFT JOIN
将包括A中的记录,而B中没有任何对应的记录.而且,COUNT
仅计算非空值,因此您需要将其与B.MemberID
一起使用.这样,由于B.MemberID
将是NULL
,因此A中在B中没有任何对应记录的记录的计数将为0.
The LEFT JOIN
will include records in A that do not have any corresponding records in B. Also, COUNT
only counts non-null values, so you need to use it with B.MemberID
. This way the count for records in A that do not have any corresponding records in B will be 0, since B.MemberID
will be NULL
.
这篇关于SQL:如何在SELECT查询结果中添加列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!