(My)SQL查询的"可选"WHERE子句

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.

ieuee的关系,因此包含外键(e_id).表示输入参数.

问题是ue.unrelated_id =?部分.我真正想做的是:

  • 当且仅当unlated_id =?存在ue关系时才返回ue.ccc.如果它不存在,我希望此字段为空.
  • 即使ulate关系为unrelated_id =?如果不存在,此查询应始终返回剩余的字段(即,对于other_id =?,保证存在).

不幸的是,如果我删除这个where子句,我会得到ue.ccc的"随机"unrelated_id.但是如果我保留它,如果这个unrelated_id不存在,查询将不会返回任何结果!我也尝试添加OR ue.unrelated_id IS NOT NULL,但如果ue表为空,这会使查询返回结果.

有任何想法吗?如果您需要进一步说明,请发表评论.我应该在接下来的几个小时内迅速回答.

Mat*_*hew 8

你可以做两件事之一:

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不是可以为空的列,则第二个查询仅适用于.