【问题标题】:"Optional" WHERE clause on (My)SQL query(My)SQL 查询上的“可选”WHERE 子句
【发布时间】:2012-08-10 17:51:51
【问题描述】:

我在 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 ...

共有三个表:ieeue

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

问题在于 ue.unrelated_id = ? 部分。我真正想在这里做的是:

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

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

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

【问题讨论】:

    标签: mysql sql left-join where-clause


    【解决方案1】:

    你可以做以下两件事之一:

    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 ...
    

    或者

    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 ...
    

    不过,我会选择第一个查询。

    编辑:请注意,仅当 ue.unrelated_id 不是可为空的列时,第二个查询才适用。

    【讨论】:

    • 完美!我不知道存在语法。谢谢! (使用查询 1)
    • 你知道如何添加可选子句 IN 吗,谢谢
    猜你喜欢
    • 2012-05-05
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多