2

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

提前致谢!

4

2 回答 2

4

你不能这样用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,但你应该避免它!:)

于 2012-05-07T12:53:13.630 回答
3

这就是你通常会如何完成这样的事情:

SELECT d.id, d.type, COALESCE(c.name, p.name)
FROM debtors d
LEFT JOIN companies c
  ON d.type = 'c' AND c.debtor_id = d.id
LEFT JOIN private_individuals p
  ON d.type = 'p' AND p.debtor_id = d.id
WHERE d.id = 1
于 2012-05-07T12:55:33.887 回答