涉及三个表的MYSQL查询中的重复结果

时间:2016-11-12 12:58:51

标签: mysql

以下MySQL查询应该列出相关的显示日期,时间以及电影“蝙蝠侠”将要播放的影院的容量。

select distinct s.Date "Showing Date", s.Time "Showing Time", t.Capacity "capacity" 
from CustomerShowing cs, Showing s, Movie m, Theatre t 
where cs.SID = s.SID and s.MID = m.MID and s.RN = t.RN and m.Name = 'Batman';

结果如下:

02-11-2016  12:35:00    17     
02-11-2016  09:30:00    5    
02-11-2016  09:30:00    5 //the second result repeated..    
02-11-2016  09:30:00    5 //and repeated again..    
02-11-2016  09:30:00    5 //etc..    
02-11-2016  09:30:00    5

什么时候应该

02-11-2016  12:35:00 17
02-11-2016  09:30:00 5

编辑:请注意,使用distinct时查询很好,我的意思是不使用distinct(!!!)

2 个答案:

答案 0 :(得分:0)

这里的问题是你在所有表上进行交叉连接,因此你得到重复。使用内部联接

select distinct s.Date "Showing Date", s.Time "Showing Time",     t.Capacity "capacity" 
from CustomerShowing cs
join Showing s on cs.SID = s.ID
join Movie m on s.MID = m.MID
join Theatre t on s.RN = t.RN
where m.Name = 'Batman';

答案 1 :(得分:0)

这将解决您的问题。这里使用了一对一的关系。

select distinct s.Date as 'Showing Date', s.Time as 'Showing Time', t.Capacity 
as 'capacity' from CustomerShowing cs INNER JOIN Showing s ON cs.SID = s.SID 
INNER JOIN Movie m ON  s.MID = m.MID INNER JOIN Theatre t ON s.RN = t.RN WHERE 
m.Name = 'Batman';

除非

select s.Date "Showing Date", s.Time "Showing Time", t.Capacity "capacity" 
from CustomerShowing cs, Showing s, Movie m, Theatre t 
where cs.SID = s.SID and s.MID = m.MID and s.RN = t.RN and m.Name = 'Batman'
group by s.Date,s.Time,t.Capacity
相关问题