如何使用 INNER JOIN 或 UNION ALL 合并 2 SELECT 语句

How To Combine 2 SELECT Statements Using INNER JOIN Or UNION ALL

我有一个 table 命名用户和疫苗,如下所示

用户

user_id first_dose second_dose
A221H MN03 PF88
C221G SV05 AZ51

疫苗

vaccine_id vaccine_name
MN03 Moderna
SV05 Sputnik V
PF88 Pfizer
AZ51 Astrazeneca
SN12 Sinopharm
CNV7 Convidecia

我想为第一个用户实现的如下所示

dose1_name dose2_name
Moderna Pfizer

这是我采用的第一种方法(仅使用 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' 

但它给出了这样的输出

dose1_name dose2_name
Moderna Moderna

我采用的第二种方法(使用 INNER JOIN 2 次)

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
- -

任何帮助将不胜感激。

你的第二种方法 2 join 是正确的,但是正如你提到的 post 的评论,应该是用户 table 然后 2 left joins to the vaccine table s

例如:

SELECT vac1.vaccine_name as dose1_name, vac2.vaccine_name as dose2_name
FROM user
LEFT JOIN vaccine as vac1 ON user.first_dose = vac1.vaccine_id
LEFT JOIN vaccine as vac2 ON user.second_dose = vac2.vaccine_id
WHERE user.user_id = 'XXXX'

另一种方法是对每个必需的连接使用相关子查询

select User_Id,
    (select vaccine_name from vaccine v where v.vaccine_id = u.first_dose) as dose1_name,
    (select vaccine_name from vaccine v where v.vaccine_id = u.second_dose) as dose2_name
from user u;

如果两个剂量并不总是填充,您可能还需要合并列。