[英]Select records with associated records of specific type
我们有2张桌子订票,票务。 Ticket.BookingId是Booking.Id的外键:
如何为仅包含类型1或3或7的票证的预订预订编写SQL select(与MS SQL Server兼容)?
如:
select Booking.Id
from Booking
join Ticket on Ticket.BookingId = Booking.Id
group by Booking.Id
having Ticket.Type IN (1,3,7)
例如,在这种情况下:
最终结果将为:2,3。
Booking.Id = 1不是最终结果,因为表中的票证是票证(Id = 4,BookingId = 1,Type = 8),因此此预订还包含除1或3或7外的其他票证类型
LINQ中的解决方案:
var result = (from b in Booking
join t in Ticket on Booing.Id equals Ticket.BooingId
group new {b,t} by b.Id).Where(group => group.Where(itemOfGroup=>itemOfGroup.Ticket.Type != 1 && itemOfGroup.Ticket.Type != 3 && itemOfGroup.Ticket.Type != 7).Count() == 0 ).Select(group => group.Key);
按预订分组,仅接受没有其他类型的那些分组
select Booking.Id
from Booking
join Ticket on Ticket.BookingId = Booking.Id
group by Booking.Id
having sum(case when Ticket.Type NOT IN (1,3,7) then 1 else 0 end) = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.