简体   繁体   English

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

[英]“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 . 有三个表: eue

Tables ie and ue are relationships of e , and therefore contain foreign keys to it (e_id). ieuee的关系,因此包含外键(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: 真正想做的是:

  • To return ue.ccc if and only if there is a ue relationship for unrelated_id = ?. 当且仅当unlated_id =?存在ue关系时才返回ue.ccc。 If it doesn't exist, I want this field to be null. 如果它不存在,我希望此字段为空。
  • Even if the ue relationship for unrelated_id = ? 即使ulate关系为unrelated_id =? doesn't exist, this query should always return the remaining fields (ie is guaranteed to exist for other_id = ?). 如果不存在,此查询应始终返回剩余的字段(即,对于other_id =?,保证存在)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM