2010-03-30 153 views
2

至於下面的語句:幫助與SQL查詢

Select * 
    From explorer.booking_record booking_record_ 
Inner Join explorer.client client_ 
    On booking_record_.labelno = client_.labelno 
Inner Join explorer.tour_hotel tour_hotel_ 
    On tour_hotel_.tourcode = booking_record_.tourrefcode 
Inner Join explorer.hotelrecord hotelrecord_ 
    On tour_hotel_.hotelcode = hotelrecord_.hotelref 
Where booking_record_.bookingdate Not Like '0000-00-00' 
    And booking_record_.tourdeparturedate Not Like '0000-00-00' 
    And (hotelrecord_.hotelgroup = "LPL" 
    And Year(booking_record_.tourdeparturedate) 
     Between Year(AddDate(Now(), Interval -5 Year)) 
      And Year(Now()) 

我的MySQL技能肯定沒有達到標準,實際的結果集我想找到的是「一個客戶誰一直到5個或更多LPL酒店在過去5年「。到目前爲止,我還沒有處理數量,因爲我得到了大量的結果,每個客戶有250多個。

我認爲這與我加入表格的方式有關。架構明智的booking_record表包含一個旅遊參考代碼,該代碼鏈接到tour_hotel然後包含一個酒店代碼鏈接到hotelrecord。此hotelrecord表包含hotelgroup。

客戶表通過預訂參考鏈接加入到booking_record,客戶可能會有很多預訂。

如果有人可以爲我提供一個方法來做到這一點,我會非常感激,並希望下次能夠自己學習!我一直在爲這個問題撓撓頭幾個小時吧!

客戶可能在booking_record內有很多預訂

Daniel。

回答

0

每一個tour_hotel酒店可能都有一個以上的酒店記錄。這就是爲什麼你有這麼多的記錄。如果你不需要關於酒店的任何信息,你可以選擇你需要從客戶端,並使用不同的。

select distinct c.clientid, c.name 
from explorer.booking_record b 
inner join explorer.client c on b.labelno = c.labelno 
inner join explorer.tour_hotel t on b.tourrefcode = t.tourcode 
inner join explorer.hotelrecord h on t.hotelcode = h.hotelref 
where 
b.bookingdate != '0000-00-00' and 
b.tourdeparturedate != '0000-00-00' and 
h.hotelgroup = "LPL" and 
year(b.tourdeparturedate) >= (year(now()) - 5) 
+0

這很好!任何想法現在我可以計數這些?我試着在最後添加一個「COUNT(booking_record_.labelno)> 5」,但結果是一行數爲109萬! – 2010-03-30 16:24:50

+0

@djfrear,你可以嘗試將GROUP BY和HAVING結合起來。 – 2010-03-30 20:56:47

0

我無法確定客戶端表上的主鍵是什麼,所以我創建了一個名爲client_id的名稱。如果你只想要客戶名單

SELECT c.client_id, h.hotelref FROM client c 
INNER JOIN booking_record b ON b.labelno = c.labelno 
INNER JOIN tour_hotel t ON t.tourcode = b.tourrefcode 
INNER JOIN hotelrecord h ON h.hotelref = t.hotelcode 
WHERE b.bookingdate > '0000-00-00' AND b.bookingdate IS NOT NULL AND 
    b.tourdeparturedate BETWEEN DATE_ADD(NOW(), INTERVAL -5 YEAR) AND NOW() AND 
    h.hotelgroup = "LPL" 
GROUP BY c.client_id, h.hotelref 
HAVING COUNT(c.client_id) > 4 

,使用DISTINCT和移除酒店:

此查詢將讓你訪問過5層或更多不同的LPL的酒店,他們參觀了酒店的客戶名單列:

SELECT DISTINCT c.client_id FROM client c 
INNER JOIN booking_record b ON b.labelno = c.labelno 
INNER JOIN tour_hotel t ON t.tourcode = b.tourrefcode 
INNER JOIN hotelrecord h ON h.hotelref = t.hotelcode 
WHERE b.bookingdate > '0000-00-00' AND b.bookingdate IS NOT NULL AND 
    b.tourdeparturedate BETWEEN DATE_ADD(NOW(), INTERVAL -5 YEAR) AND NOW() AND 
    h.hotelgroup = "LPL" 
GROUP BY c.client_id, h.hotelref 
HAVING COUNT(c.client_id) > 4 
+0

感謝馬庫斯 - 第二個查詢完全按照我希望的那樣完成了 – 2010-03-31 09:24:04

+0

也許不是,我看起來好像還是比預期的要大得多 - 幾乎每個記錄都有數百個,有些超過1000個。期望結果真的不到20。 – 2010-03-31 09:42:38

+0

@djfrear,那麼在連接中可能會發生一些事情。您可能想要爲這些表發佈架構。 – 2010-03-31 12:43:05