两个查询,重复结果

时间:2014-08-13 16:13:25

标签: mysql

我在数据库中有以下两个表

" rn_slots_availability"

id|room_type_id|slot_avail_clean|slot_avail_noclean|slot_date  |hotel_id
1 |6           |7               |9                 |2014-08-12 |5
2 |7           |8               |2                 |2014-08-12 |5
3 |7           |9               |9                 |2014-08-13 |5
4 |6           |9               |9                 |2014-08-13 |5

" rn_slots_prices"

id|slot_date  |slot_time |slot_price|hotel_id|room_type_id|status
18|2014-08-12 | 01:00:00 |26        |5       |6           |1
19|2014-08-12 | 00:00:00 |15        |5       |6           |1
20|2014-08-12 | 00:00:00 |20        |5       |7           |1
21|2014-08-11 | 02:00:00 |14        |5       |6           |1

我想最终得到这样的数组:

[2014-08-12] => Array
    (
        [00:00:00] => Array
            (
                [6] => Array
                    (
                        [price] => 15
                        [avail_clean] => 7
                        [avail_noclean] => 9
                    )

                [7] => Array
                    (
                        [price] => 20
                        [avail_clean] => 8
                        [avail_noclean] => 2
                    )

            )

    )

通过查询,我得到重复的条目:

SELECT 
    DISTINCT(rn_slots_availability.slot_avail_clean), 
    rn_slots_availability.room_type_id, 
    rn_slots_prices.slot_price, 
    rn_slots_prices.slot_time, 
    rn_slots_availability.slot_date, 
    rn_slots_availability.slot_avail_noclean   
FROM 
    rn_slots_availability, rn_slots_prices 
WHERE  
    rn_slots_prices.hotel_id = 5 
AND 
    rn_slots_prices.slot_date = '2014-08-12' 
AND 
    rn_slots_availability.slot_date = '2014-08-12' 
AND 
    rn_slots_prices.slot_time = '00:00:00' 

如果没有两个separte查询,应该知道正确的查询应该如何?

由于

编辑:看到这个小提琴:http://sqlfiddle.com/#!2/48e1e/2/0

1 个答案:

答案 0 :(得分:1)

我认为您需要这样的查询:

SELECT 
    sp.room_type_id, 
    sp.slot_price, 
    sp.slot_time, 
    sp.slot_date, 
    sa.slot_avail_clean, 
    sa.slot_avail_noclean   
FROM rn_slots_prices       sp
JOIN rn_slots_availability sa ON
  sa.hotel_id     = sp.hotel_id     AND
  sa.room_type_id = sp.room_type_id AND
  sa.slot_date    = sp.slot_date
WHERE  
    sp.hotel_id  =  5           AND 
    sp.slot_date = '2014-08-12' AND 
    sp.slot_time = '00:00:00' 

只需在逻辑关系键上加入两个表,然后根据需要过滤数据。在这种情况下,我将所有WHERE条件放在slot_prices表上。

在这种情况下,您不需要DISTINCT。我还使用表别名来使查询更具可读性。