我们有 2 张 table 预订,门票。 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 不在最终结果中,因为表 Ticket 中是票证(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
关于sql - 选择具有特定类型关联记录的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39035622/