SQL的新手,我建立了一个数据库,用于存储有关公司的信息。在下面的查询中,我试图显示创始人和首席执行官的名字,但是我得到了歧义性错误。
我将Founder表和CEO表连接到人员表,该人表存储了CEO /创始人的名字和姓氏。在所有3个表之间共享的外键是pid(人员ID)。尝试返回名称时,我的select语句遇到了问题。然后,我尝试从列名(founder.first_name和ceo.first_name)中添加连接的表名,但这没用。
SELECT co.ein,
company_name as Company,
CONCAT(fo.first_name,' ',fo.last_name) as Founder,
CONCAT(ceo.first_name,' ',ceo.last_name) as CEO,
CASE
WHEN last_price IS NULL THEN '-'
ELSE CONCAT('$',FORMAT(last_price,2))
END as 'Current Stock Price'
FROM company co
LEFT JOIN stock s ON co.ein = s.ein
LEFT JOIN ceo ON co.ein = ceo.ein
LEFT JOIN founder fo ON co.ein = fo.ein
LEFT JOIN person p ON ceo.pid = p.pid
LEFT JOIN person ON fo.pid = p.pid
我需要返回公司名称,创始人名称,首席执行官名称和当前股价。
答案 0 :(得分:0)
您需要为人员提供两个别名(例如p1和p2),并且应使用完全限定的列名
SELECT co.ein,
co.company_name as Company,
CONCAT(fo.first_name,' ',fo.last_name) as Founder,
CONCAT(ceo.first_name,' ',ceo.last_name) as CEO,
CASE
WHEN s.last_price IS NULL THEN '-'
ELSE CONCAT('$',FORMAT(s.last_price,2))
END as 'Current Stock Price'
FROM company co
LEFT JOIN stock s ON co.ein = s.ein
LEFT JOIN ceo ON co.ein = ceo.ein
LEFT JOIN founder fo ON co.ein = fo.ein
LEFT JOIN person p1 ON ceo.pid = p1.pid
LEFT JOIN person p2 ON fo.pid = p2.pid