如何使用内在或联合组合2个选择语句
I have a table named user and vaccine like below
user
user_id | first_dose | second_dose |
---|---|---|
A221H | MN03 | PF88 |
C221G | SV05 | AZ51 |
vaccine
vaccine_id | vaccine_name |
---|---|
MN03 | Moderna |
SV05 | Sputnik V |
PF88 | Pfizer |
AZ51 | Astrazeneca |
SN12 | Sinopharm |
CNV7 | Convidecia |
我想为第一用户实现的目标是下面的
dose1_name | dose2_name |
---|---|
moderna | pfizer |
这是我采用的第一个方法(仅使用1个内部加入),
SELECT vaccine_name AS dose1_name, vaccine_name AS dose2_name FROM vaccine INNER JOIN user ON first_dose = vaccine.vaccine_id WHERE user.user_id = 'A221H'
一样的输出
但它给出了像dose1_name dose1_name | dose2_name |
---|---|
Moderna | Moderna |
,我采用的第二种方法是我采用的第二种方法),
SELECT vac_name AS dose1_name, vac_name AS dose2_name FROM vaccine INNER JOIN user fd ON fd.first_dose = vaccine.vaccines_id INNER JOIN user sd ON sd.second_dose = vaccine.vaccines_id WHERE fd.user_id = 'A221H' AND sd.user_id = 'A221H'
没有输出
dose1_name | dose2_name-- |
---|---|
但它 | 将不胜 |
感激。
I have a table named user and vaccine like below
user
user_id | first_dose | second_dose |
---|---|---|
A221H | MN03 | PF88 |
C221G | SV05 | AZ51 |
vaccine
vaccine_id | vaccine_name |
---|---|
MN03 | Moderna |
SV05 | Sputnik V |
PF88 | Pfizer |
AZ51 | Astrazeneca |
SN12 | Sinopharm |
CNV7 | Convidecia |
What i want to achieve for 1st user is like below
dose1_name | dose2_name |
---|---|
Moderna | Pfizer |
Here is the 1st approach i took (using only 1 INNER JOIN)
SELECT vaccine_name AS dose1_name, vaccine_name AS dose2_name FROM vaccine INNER JOIN user ON first_dose = vaccine.vaccine_id WHERE user.user_id = 'A221H'
But it gives output like this
dose1_name | dose2_name |
---|---|
Moderna | Moderna |
The 2nd approach i took (using INNER JOIN 2 times)
SELECT vac_name AS dose1_name, vac_name AS dose2_name FROM vaccine INNER JOIN user fd ON fd.first_dose = vaccine.vaccines_id INNER JOIN user sd ON sd.second_dose = vaccine.vaccines_id WHERE fd.user_id = 'A221H' AND sd.user_id = 'A221H'
But it gives no output
dose1_name | dose2_name |
---|---|
- | - |
Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第二种方法的第二种方法是正确的,但是作为对您提到的帖子的评论,它应该是用户表,然后2个将加入到疫苗表上
:例如:
Your second approach of 2 joins is correct, however as a comment on your post mentioned, it should be the users table and then 2 left joins to the vaccine tables
For example:
一种替代方法是使用相关的子查询进行所需的加入:
如果两种剂量并不总是填充,则可能需要 cocce 。
An alternative is to use a correlated subquery for each required join:
you may also need to coalesce the columns if both doses are not always populated.