使用左连接和并集选择

fslejnso  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(213)

我有一个查询,返回某个员工轮班时的发票

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表中获取employee name,而我只有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语句有不同的列数

5w9g7ksd

5w9g7ksd1#

关于这个问题,错误消息非常清楚:第一个查询返回8列数据,而第二个查询只返回1列数据,因此不能 UNION 他们。看来你可能想 JOIN 这个 employee 通过表格 shift 表e.g。

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

相关问题