我总是在PHP或ASAP中做到这一点,所以我觉得是时候实际学习在SQL中使用它的正确方法了。我在数据库中有以下4个表:
类别(字段:CategoryNumber,Desc)(包含15行的小表)
媒体(字段:MediaID,Desc,CategoryNumber等)(包含15,000行的大表)
销售(字段:日期,MediaID,EmployeeID等)(包含100,000行的大表)
员工(字段:EmployeeID,名称等)(只有20行的小表)
仅限类别链接到媒体 媒体有类别和销售的链接。 销售链接到媒体和员工 员工只链接到销售
我想做的是写一个查询,告诉我某个员工从未销售任何媒体的类别。
我可以编写一个简单的查询来查找2个表之间的不匹配数据,但是当我处理4个表时,我不知道如何做到这一点。
感谢您的时间和帮助!
答案 0 :(得分:3)
这是我的建议:
select *
from Category c
where not exists (
select *
from Employee e
inner join Sales s on s.EmployeeId = e.EmployeeId
inner join Media m on m.MediaID = s.MediaID
where e.Name = 'Ryan' and m.CategoryNumber = c.CategoryNumber
)
要查询所有未出售任何类别的雇员:
select e.EmployeeName, c.CategoryNumber
from Category c
cross join Employee e
where not exists (
select *
from Sales s
inner join Media m on m.MediaID = s.MediaID
where c.categoryNumber = m.CategoryNumber
and s.EmployeeId = e.EmployeeId
)
答案 1 :(得分:2)
SELECT c.CategoryNumber, c.Desc
FROM Category c
WHERE NOT EXISTS
(
SELECT *
FROM Employees e
INNER JOIN Sales s on s.EmployeeID = e.EmployeeID
INNER JOIN Media m on m.MediaID = s.MediaID
WHERE e.Name = "Ryan"
AND m.CategoryNumber = c.CategoryNumber
)
MS Access显然需要很多括号(谢谢,Ryan!):
select *
from Category c
where not exists
( select *
from ( Employee e
inner join Sales s on (s.EmployeeId = e.EmployeeId))
inner join Media m on (m.MediaID = s.MediaID)
where (e.Name = 'Ryan' and m.CategoryNumber = c.CategoryNumber) )
答案 2 :(得分:1)
select c.desc
from category
left outer join (select s.employeeid,m.categorynumber
from sales s
inner join media m on s.mediaid=m.mediaid
inner join employee e on e.employeeid=s.employeeid
where e.name = 'JOE'
group by employeeid,categorynumber) t on t.categorynumber=c.categorynumber
where s.employeeid is null
答案 3 :(得分:0)
根据Carl在Access SQL语法中提供的解决方案修改了答案:
select *
from Category c
where not exists (
select *
from (Employee e
inner join Sales s on (s.EmployeeId = e.EmployeeId))
inner join Media m on (m.MediaID = s.MediaID)
where (e.Name = 'Ryan' and m.CategoryNumber = c.CategoryNumber)
)