2015-06-13 19 views
1

嗨,我想問你的幫助,我得到了一個問題。我有一個酒店的數據庫,我想找到最長的住宿客戶。SQL最長留

我有3個表:

  1. 負荷消費(code_costumer,名字,姓氏),
  2. 住宿(code_stay,DATE_START,DATE_END)
  3. costumer_stay(code_stay,code_costumer )

我創建的腳本:

SELECT datediff(date_end,date_start) as dd, 
     stay.code_stay,costumer_stay.code_costumer 
FROM stay INNER JOIN costumer_stay 
      ON stay.code_stay=costumer_stay.code_stay; 

,但我不能讓一個人與停留時間最長,我得到類似的東西:

id|code_stay|code_costumer| 
--------------------------- 
25|xa21  |1001   | 
8 |xb24  |1005   | 
7 |xb30  |1003   | 

回答

2
SELECT datediff(date_end,date_start) as dd, 
     stay.code_stay,costumer_stay.code_costumer 
FROM stay 
INNER JOIN costumer_stay ON stay.code_stay = costumer_stay.code_stay 
ORDER BY dd desc 
LIMIT 1 
+0

爲了找到前1的結果,應避免使用'order by'。這樣排序整個表,然後給出一個結果。 – twentylemon

+0

非常感謝你完成了這份工作 – Kostasfra

+0

@twentylemon:如果不通過所有的值,你還認爲DB如何確定表的最大價值? –

1

select code_stay from stay where datediff(date_end,date_start) = (
    select max(datediff(date_end,date_start)) from stay 
) 

應該工作

+0

外貌對我好。它出什麼問題了? – twentylemon

+0

我的不好。沒有看到最後一個單獨的行。 –