MySQL查询是否加入

时间:2016-01-30 20:57:35

标签: mysql pdo

SELECT * FROM bn_garant_tpl 
JOIN bn_garant_val
WHERE bn_garant_tpl.what_tpl IN (1, 2)
AND bn_garant_tpl.id_tpl = bn_garant_val.id_garant_tpl
ORDER BY ords ASC

如何获取what_tpl = 1的行?

问题是下一个:在表bn_garant_val中不存在行如果what_tpl = 1 。仅适用于 if what_tpl = 2

如果ID匹配

,则返回此查询
AND bn_garant_tpl.id_tpl = bn_garant_val.id_garant_tpl

但是,结果必须是:如果 what_tpl = 1 也是

1 个答案:

答案 0 :(得分:1)

如果您需要bn_garant_tpl中的记录,即使bn_garant_val中没有此类记录,请使用LEFT JOIN

SELECT * FROM bn_garant_tpl 
LEFT JOIN bn_garant_val ON bn_garant_tpl.id_tpl = bn_garant_val.id_garant_tpl
WHERE bn_garant_tpl.what_tpl IN (1, 2)
ORDER BY ords ASC