我想获取ProductId
尚未订购的Employee
列表。
我有这个查询,它给了我所有已订购的ProductId
,但我想要反过来:
select distinct e.EmployeeID ,p.ProductID from Products p
join OrderDetails od on od.ProductID=p.ProductID
join Orders o on o.OrderID=od.OrderID
join Employee e on e.EmployeeID=o.EmployeeID order by e.EmployeeID
答案 0 :(得分:1)
使用left join
并查看NULL
:
select distinct e.EmployeeID ,p.ProductID
from Products p
left join OrderDetails od on od.ProductID=p.ProductID
left join Orders o on o.OrderID=od.OrderID
left join Employee e on e.EmployeeID=o.EmployeeID
where e.EmployeeName IS NULL
order by e.EmployeeID
如果Employee
表中没有关联的员工记录,则会返回订单详细信息。
修改强>
试试这个:
select e1.EmployeeID,p1.ProductID
from Employee e1, p1.ProductID
where e1.EmployeeID NOT IN
( select distinct e.EmployeeID from Products p
join OrderDetails od on od.ProductID=p.ProductID
join Orders o on o.OrderID=od.OrderID
join Employee e on e.EmployeeID=o.EmployeeID)
and p1.ProductID NOT IN
( select distinct p.ProductID from Products p
join OrderDetails od on od.ProductID=p.ProductID
join Orders o on o.OrderID=od.OrderID
join Employee e on e.EmployeeID=o.EmployeeID)
如果您提供一些示例数据和表格结构,我们可以进行更好的查询。
答案 1 :(得分:0)
试一试 -
select distinct e.EmployeeID ,p.ProductID
from Products p
join OrderDetails od on od.ProductID=p.ProductID
join Orders o on o.OrderID=od.OrderID
left join Employee e on e.EmployeeID=o.EmployeeID
where e.EmployeeID is null
order by o.EmployeeID;