选择左连接和联合

问题描述 投票:0回答:1

我有这个查询返回在某个员工班次上发出的发票

SELECT
i.dateTime,i.amount,i.totalProfit,i.shiftID,
i_o.itemID,i_o.quantity,
item.name itemName,
p.full_name

from invoice i 

LEFT JOIN 
inv_order i_o on i_o.invID=i.invID

LEFT JOIN 
`item-service` item on item.itemID = i_o.itemID


LEFT JOIN person p on 
p.PID=i.personID

where i.shiftID =97

但是,我需要从employee表中获取员工姓名,而我只有shiftID。

SELECT
i.dateTime,i.type,i.amount,i.totalProfit,i.shiftID,i_o.itemID,i_o.quantity,item.name itemName,p.full_name

from invoice i 

LEFT JOIN 
inv_order i_o on i_o.invID=i.invID

LEFT JOIN 
`item-service` item on item.itemID = i_o.itemID


LEFT JOIN person p on 
p.PID=i.personID

where i.shiftID =97

UNION

SELECT e.name from employee e

left join shift s on s.empID = e.empID

where s.shiftID =97

mysql返回此错误

使用的SELECT语句具有不同的列数

mysql select left-join union unions
1个回答
1
投票

关于问题的错误信息非常清楚:您的第一个查询返回8列数据而第二个查询只返回1,因此您无法UNION它们。看起来你可能想通过JOIN表只需employee shift表,例如

SELECT i.dateTime
      ,i.type
      ,i.amount
      ,i.totalProfit
      ,i.shiftID
      ,i_o.itemID
      ,i_o.quantity
      ,item.name AS itemName
      ,p.full_name
      ,e.name
FROM invoice i 
LEFT JOIN inv_order i_o ON i_o.invID=i.invID
LEFT JOIN `item-service` item ON item.itemID = i_o.itemID
LEFT JOIN person p ON p.PID=i.personID
LEFT JOIN shift s ON s.shiftID = i.shiftID
LEFT JOIN employee e ON e.empID = s.empID
WHERE i.shiftID = 97
© www.soinside.com 2019 - 2024. All rights reserved.