嗨,大家好我想尝试做像
这样的事情SELECT * from accounttable, peopletable, companytable
WHERE if accounttable.account_type = company
JOIN companytable
WHERE companytable.id = accounttable.company_id
ELSE IF accounttable.account_type = = person
JOIN peopletable
WHERE peopletable.id = accounttable.person_id
对不起它有点sqlenglish但我真的不知道如何写出来!
答案 0 :(得分:15)
如下:
SELECT *
from accounttable
left join peopletable ON (accounttype = 'person' AND peopletable.id = accounttable.person_id)
left join companytable ON (accounttype = 'company' AND companytable.id = accounttable.company_id)
我将加入两个表,因此您将在输出中包含所有三个表的字段。如果peopletable
,NULL
的字段将为accounttype != 'person'
,companytable
的字段将为NULL
accounttype != 'company'
。
您可以在here ...
等地方找到有关LEFT JOIN
语法的更多信息
答案 1 :(得分:6)
SELECT a.*, p.*, c.* from accounttable a
LEFT JOIN peopletable p ON (a.person_id = p.id AND a.account_type = 'person')
LEFT JOIN companytable c ON (a.company_id = c.id AND a.account_type = 'company')
请注意,a,p,c是完整表名的别名,这可以节省输入。
此查询将为行中的所有null
提供p。*或c。*
您可以像这样重写选择部分:
SELECT
a.id, a.accounttype
, COALESCE(p.name, c.name) as name
, COALESCE(p.address, c.address) as address
....
FROM .....
请参阅:http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce
答案 2 :(得分:0)
必须如下(据我所知)
SELECT a.*,p.*,c.*
FROM accounttable a
LEFT JOIN companytable c ON c.id = a.company_id AND a.account_type = 'company'
LEFT JOIN peopletable p ON p.id = a.person_id AND a.account_type = 'person'