如何确定两张表的关联关系(一对一,一对多,多对多)

假设两张表

tab_A                        tab_B

id                            id
1                             1
2                             1
3                             3
3                             5
4                             6
7                             7
select a.id, b.id from  tab_A a, tab_B b where a.id = b.id


a.id               b.id
1                   1
1                   1
3                   3
3                   3
7                   7

 1,确定关联字段在表中是否唯一

select id, count(1) num from tab_A group by id having num > 1
若有返回,则说明该字段不唯一
若没有返回,则说明该字段唯一

select id, count(1) num from tab_B group by id having num > 1
若有返回,则说明该字段不唯一
若没有返回,则说明该字段唯一

(1)如果tab_A的id字段唯一, tab_B的id字段唯一,则是一对一的关系

(2)如果tab_A的id字段唯一, tab_B的id字段不唯一,则是一对多的关系

(3)如果tab_A的id字段不唯一, tab_B的id字段唯一,则是多对一的关系

(4)如果tab_A的id字段不唯一, tab_B的id字段不唯一,则是多对多的关系

2,查询出字段值存在一对多的关系 

select 
    aa.id,
    aa.num
from
(
    select 
        a.id, count(1) num
    from
        tab_A a,
        tab_B b
    where a.id = b.id 
    group by a.id
)aa
where aa.num > 1

注:group by a.id还是group by b.id结果都是一样

发布了348 篇原创文章 · 获赞 210 · 访问量 87万+

猜你喜欢

转载自blog.csdn.net/u010916338/article/details/103700659
今日推荐