[英]“Optional” WHERE clause on (My)SQL query
I'm having a bit of a problem with a SELECT query in MySQL and I'd be thankful for some pointers. 我在MySQL中遇到一个SELECT查询有点问题,我会感谢你的一些指示。 Please feel free to point me towards an existing answer (if there is one and I missed it). 请随时指出我现有的答案(如果有的话我错过了)。
The query is currently as follows: 查询目前如下:
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 ...
There are three tables: ie , e and ue . 有三个表: 即 e和ue 。
Tables ie and ue are relationships of e , and therefore contain foreign keys to it (e_id). 表ie和ue是e的关系,因此包含外键(e_id)。 ? ? represents an input parameter. 表示输入参数。
The problem is the ue.unrelated_id = ? 问题是ue.unrelated_id =? part. 部分。 What I'm really trying to do here is: 我真正想做的是:
Unfortunately, if I remove this where clause, I get ue.ccc for a "random" unrelated_id. 不幸的是,如果我删除这个where子句,我会得到ue.ccc的“随机”unrelated_id。 But if I keep it, the query won't return any results at all if ue doesn't exist for this unrelated_id! 但是如果我保留它,如果这个unrelated_id不存在,查询将不会返回任何结果! I also tried adding OR ue.unrelated_id IS NOT NULL, but this makes the query return no results if the ue table is empty. 我也尝试添加OR ue.unrelated_id IS NOT NULL,但如果ue表为空,这会使查询返回结果。
Any ideas? 有任何想法吗? Please drop a comment if you need further clarification. 如果您需要进一步说明,请发表评论。 I should answer quickly in the next few hours. 我应该在接下来的几个小时内迅速回答。
You could do one of two things: 你可以做两件事之一:
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 ...
Or 要么
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 ...
I would go with the first query, however. 不过,我会选择第一个查询。
EDIT: Please note that the 2nd query is only approperiate if ue.unrelated_id
is not a nullable column. 编辑:请注意,如果ue.unrelated_id
不是可空列,则第二个查询仅适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.