SELECT 中的 MySQL IF

标签 mysql sql

我有三个 MySQL InnoDB 表: 债务人 公司 个人

现在我想查找有关债务人的信息。 以下 SQL 不工作,任何人都可以帮助我编写工作 SQL 吗?

SELECT
    d.id,
    d.type,
    i.name
FROM
    debtors AS d
IF d.type = 'c' THEN
    INNER JOIN
        companies AS i ON (i.debtor_id = d.id)
ELSE THEN
    INNER JOIN
        private_individuals AS i ON (i.debtor_id = d.id)
WHERE
    d.id = 1

错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF d.type = 'c' THEN INNER JOIN companies AS i ON (i.debtor_id = d.i' at line 7

提前致谢!

最佳答案

你不能那样使用 IF!

这是一个可能的解决方案:

SELECT
    d.id,
    d.type,
    COALESCE(i.name, i2.name) as name
FROM
    debtors AS d
    LEFT JOIN companies AS i ON i.debtor_id = d.id and d.type = 'c'
    LEFT JOIN private_individuals AS i2 ON i2.debtor_id = d.id and d.type <> 'c'
WHERE
    d.id = 1

另一个可能是动态 SQL,但您应该避免使用它! :)

关于SELECT 中的 MySQL IF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10482366/

相关文章:

mysql - 根据另一列获取最小出现次数

sql - 乔姆拉。在 bluehost 服务器上移动网站并为新域手动导入 sql 数据库后,在 JError 中检测到无限循环?

MySQL – group by 区间查询优化

php - 请求有关基本 php PDO 连接的帮助

php - 从多列mysql中选择值

mysql - 我如何获得以字母开头并继续下一个字母的列表?

mysql 使用外部别名进行 2 级深度子查询

MySQL SELECT 基于第二个字段值

mysql - 从多列中选择最小值然后计算它们的总和的最佳方法是什么?

mysql - 两个连接查询需要 540 秒才能运行 - 我怎样才能加快速度?