Pro*_*ted 3 mysql sql left-join where-clause
我在MySQL中遇到一个SELECT查询问题,我会感谢一些指针.请随时指出我现有的答案(如果有的话我错过了).
查询目前如下:
SELECT e.*, ie.aaa, ue.bbb, ue.ccc
FROM ie
LEFT JOIN e ON ie.e_id = e.e_id
LEFT JOIN ue ON ie.e_id = ue.e_id
WHERE ie.other_id = ? AND ue.unrelated_id = ?
ORDER BY ...
Run Code Online (Sandbox Code Playgroud)
有三个表:即,ê和UE.
表ie和ue是e的关系,因此包含外键(e_id).?表示输入参数.
问题是ue.unrelated_id =?部分.我真正想做的是:
不幸的是,如果我删除这个where子句,我会得到ue.ccc的"随机"unrelated_id.但是如果我保留它,如果这个unrelated_id不存在,查询将不会返回任何结果!我也尝试添加OR ue.unrelated_id IS NOT NULL,但如果ue表为空,这会使查询返回结果.
有任何想法吗?如果您需要进一步说明,请发表评论.我应该在接下来的几个小时内迅速回答.
你可以做两件事之一:
SELECT e.*, ie.aaa, ue.bbb, ue.ccc
FROM ie
LEFT JOIN e ON ie.e_id = e.e_id
LEFT JOIN ue ON ie.e_id = ue.e_id AND ue.unrelated_id = ?
WHERE ie.other_id = ?
ORDER BY ...
Run Code Online (Sandbox Code Playgroud)
要么
SELECT e.*, ie.aaa, ue.bbb, ue.ccc
FROM ie
LEFT JOIN e ON ie.e_id = e.e_id
LEFT JOIN ue ON ie.e_id = ue.e_id
WHERE ie.other_id = ? AND (ue.unrelated_id IS NULL OR ue.unrelated_id = ?)
ORDER BY ...
Run Code Online (Sandbox Code Playgroud)
不过,我会选择第一个查询.
编辑:请注意,如果ue.unrelated_id不是可以为空的列,则第二个查询仅适用于.
| 归档时间: |
|
| 查看次数: |
4686 次 |
| 最近记录: |