gpt4 book ai didi

SELECT 中的 MySQL IF

转载 作者:行者123 更新时间:2023-11-29 01:17:51 26 4
gpt4 key购买 nike

我有三个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com