简体   繁体   English

将两个选择合并为一个

[英]Combine two selects into one

I have a couple of tables. 我有几张桌子。 I'll try to make it simple: Table_1 ID is unique. 我将尝试使其变得简单:Table_1 ID是唯一的。 Table_2 ID is not unique. Table_2 ID不是唯一的。 The table_2 stores the ID from a row on table_1 and a value, resulting in, for instance, this: table_2存储来自table_1上一行的ID和一个值,例如,得出以下结果:

table_1
ID | A
------
1  | a
2  | b
3  | c

table_2
ID | B
------
1  | x
1  | y
3  | z

I want to count how many of each ID is there on table_2, so I do 我想计算table_2上每个ID的数量,所以我

select t1.id, count(*)
from table_1 t1
group by t1.id

id | count
----------
1  | 2
3  | 1

And I want to list every row on table_2 and its corresponding value on table_1.A, so I do 我想列出table_2上的每一行,并在table_1.A上列出其对应的值,所以我这样做

select t1.id, t1.A, t2.B
from table_2 t2
left join table_1 t1
on t1.id = t2.id

ID | A | B
----------
1  | a | x
1  | a | y
3  | c | z

Is there a way to combine those 2 selections into one, to get a result like this? 有没有一种方法可以将这两个选择合并为一个,以获得类似的结果?

ID | A | B | count
------------------
1  | a | x | 2
1  | a | y | 2
3  | c | z | 1

You can combine the results by joining the count result. 您可以通过加入count结果来合并结果。

Fiddle with sample data 摆弄样本数据

select t1.id, t1.A, t2.B, x.cnt as count
from  t2
left join t1
on t1.id = t2.id
join (select t2.id, count(*) as cnt
from  t2
group by t2.id
) x
on x.id = t1.id

Besides the generic Derived Table solution posted by @vkp you might also utilize a Scalar Subquery to return a single value: 除了@vkp发布的通用派生表解决方案之外,您还可以利用标量子查询返回单个值:

select t1.id, t1.A, t2.B, 
 (select count(*)
  from  t2 as x
  where x.id = t2.id
) cnt
from  t2

http://www.sqlfiddle.com/#!9/07a3a/6 http://www.sqlfiddle.com/#!9/07a3a/6

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

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