根据id合并两个表 [英] Merging two tables based on id

查看:137
本文介绍了根据id合并两个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用table2的列附加table1时遇到问题



表用户(id,name,Gender)

表资格(id ,姓名)

多对多关系



让我们说用户表如下

id,name,性别

1,约翰,男性

2,史密斯,男性

3,凯瑟琳,女性



资格表

User_id,学位

1,Msc

1,BSC

3 ,Msc



我想要的是...得到一个结果表格为



id,name,性别,学位

1,john,男,Msc

1,john,男,Msc

2,史密斯,男,null /或保持空白

3,凯瑟琳,女,Msc



我尝试过:



我试过

选择u.id,u.name,u.gender,q.degree

FROM user as u

INNER JOIN资格为q

ON u.id = q.User_id





我知道他们这样做错误.. :(但找不到任何解决方案

facing problem in appending table1 with the columns of table2

Table User (id, name, Gender)
Table Qualification(id, name)
many to many relationship

Lets Say User Table is as Below
id, name, gender
1, john, male
2, smith, male
3,catherine, female

Qualification Table
User_id, Degree
1, Msc
1,BSC
3,Msc

What i want is.. to get a resultant table as

id, name, gender, Degree
1,john,male,Msc
1,john,male,Msc
2,smith,male,null/or remains empty
3,catherine,female,Msc

What I have tried:

i've tried
Select u.id, u.name, u.gender, q.degree
FROM user as u
INNER JOIN qualification as q
ON u.id=q.User_id


I know em doing it wrong way.. :( but couldn't find any solution

推荐答案

更改INNER JOIN LEFT OUTER JOIN





你可以发现这篇文章很有用 SQL连接的可视化表示 [ ^ ]



另外,避免使用保留字作为表名或列名,如果你真的必须用方括号括起来,例如 [user]


您还必须更改查询顺序以及加入类型



you'd have to change the order of query also as well as the type of join

select *
from qualifications a left outer join [user] b
on a.user_id = b.id
where b.id is not null


这篇关于根据id合并两个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆