【问题标题】:In one-to-many relationship tables, get only those rows from table A that have multiple corresponding rows in table B在一对多关系表中,仅获取表 A 中在表 B 中有多个对应行的行
【发布时间】:2020-04-07 09:41:06
【问题描述】:

我有两个具有 一对多 关系的表。
AB

A有两个属性:pkAname
B有三个属性:pkBnamepkA,其中pkA 存储表 ApkA

现在我想编写一个查询,它只给我那些在表 B 中有多个对应条目的表 A 的名称。


例子-

一个

a1     name1
a2     name2
a3     name3

B

b1    name1    a1
b2    name2    a1
b3    name3    a3    

查询必须只返回 a1, name1,因为只有 a1 在表 B 中有多个引用。

【问题讨论】:

  • 您可以COUNT pkB 行数并在HAVING 子句中使用它。你试过什么?

标签: sql join one-to-many


【解决方案1】:

你可以使用聚合和having:

select pkA
from b
group by pkA
having count(*) > 1;

【讨论】:

    猜你喜欢
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多