【问题标题】:fetch from table with conditions从有条件的表中获取
【发布时间】:2014-04-06 10:35:12
【问题描述】:

我有两张表hotels 和company_hotels。其中hotel表由Id、Hotel_Name、Destination_Id组成,company_hotels由Id、Company_Id、Hotel_Id组成。我想搜索具有公司 ID 1 和 2 且 Destination_Id = 10 的相同酒店

酒店餐桌

1 hotel 1 10
2 hotel 2 11
3 hotel 3 10

公司酒店

1 1 1
2 1 3
3 2 1

对于上面的示例,我需要结果酒店 1 作为结果

【问题讨论】:

    标签: mysql


    【解决方案1】:

    这应该可以解决问题

    select h.Id,h.Hotel_Name
    from hotel h
    inner join  company_hotels ch on ch.Hotel_Id = h.Id
    where 
    ch.Company_Id IN (1,2)
    AND h.Destination_Id = 10
    

    更新 1

    从更新后的 cmets 中,查询应该返回同时具有公司 ID 1 和 2 的酒店,而不是所有具有 1 或 2 的酒店

    select h.Id,h.Hotel_Name
    from hotels h
    inner join  company_hotels ch on ch.Hotel_Id = h.Id
    where 
    ch.Company_Id IN (1,2)
    AND h.Destination_Id = 10
    group by h.Id
    having count(h.Id) = 2
    

    http://sqlfiddle.com/#!2/9025d/3

    【讨论】:

    • 但它会给出公司 ID 为 1 和 2 的所有酒店。我只想要相同的酒店。
    • 你的意思是一个酒店可以有2个公司ID?
    • 是的。我更新了上述问题中的一些数据。表示 company1 和 2 在目的地 10 中选择 hotel1
    • 检查此sqlfiddle.com/#!2/9025d/2 并请使用您期望的数据更新问题。
    • 对于你的例子,我只需要酒店 aa。因为aa同时满足destination id = 10 和company id = 1 and 2
    【解决方案2】:

    加入hotel_id

    Select * from company_hotels inner join hotel
    on hotel.id=company_hotels.hotel_id 
    where company_hotel.company_id in (1,2) 
    and hotel.destination_id=10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 2022-01-01
      相关资源
      最近更新 更多