2016-09-15 70 views
6

我有3個MySQL表(訂單,營,用戶)爲波紋管的值,的MySQL得到最後2條記錄表有3個表

order_table 
ID camp_id  orderDate  message 
1  1   2015-01-01  ok 
2  1   2015-02-01  ok 
3  2   2015-03-01  not ok 
4  3   2015-01-01  not ok 
5  1   2015-04-01  not ok 
6  2   2015-01-01  ok 
7  3   2015-07-01  not ok 

camp_table 
camp_id camp_uid  camp name 
1  10    first camp 
2  11    second camp 
3  12    third camp 
4  10    forth camp 

user_table 
uid uname 
10  abc 
11  xyz 
12  wrt 

我想有結果作爲波紋管

uname,camp name,message 

通過orderDate存儲

最後2個記錄從order_table每個用戶爲今天爲了我想加盟SE表, E從camp_table消息order_tableUNAMEUSER_TABLE營南。 爲今天爲了通過orderDate存儲 感謝

+0

請編輯並更詳細地解釋您的問題。 – FluxCoder

+0

您想要訂購故事中最後2條記錄,並且您希望我們加入? –

+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

回答

2
SELECT 
    u.uname, 
    ct.camp_name, 
    ot.message 
FROM 
    (
     SELECT 
      * 
     FROM 
      order_table o1 
     WHERE 
      (
       SELECT 
        COUNT(*) 
       FROM 
        order_table o2 
       WHERE 
        o1.camp_id = o2.camp_id 
       AND o2.ID >= o1.ID 
      ) <= 2 
    ) ot 
INNER JOIN camp_table ct ON ct.camp_id = ot.camp_id 
INNER JOIN user_table u ON ct.camp_uid = u.uid 
ORDER BY 
    u.uname 
+0

你好,這是無休止的查詢和mysql卡住 –

+0

它適用於我的系統,與您的問題中的數據庫值。 –

+0

是@ShoyebSheikh,對我來說你的查詢也有效 –

-3

使用下面的SQL查詢

"select uname, camp name, message from (order join camp on order.camp_id = camp.camp_id) join user on and camp.camp_uid = user.uid order by order.orderdate desc limit 2" 

希望它能幫助。

+0

你應該使用連接而不是在哪裏連接表 –

+0

是的!那就對了。我剛纔提到該死的簡單方法去做 –

+0

「該死的簡單方法」是一個非常老式的,不再被使用,只爲你知道:) –

3
Select 
ct.camp_name, 
ut.uname, 
ot.message FROM order_table as ot 
LEFT JOIN camp_table as ct on ot.camp_id = ct.camp_id 
LEFT JOIN user_table as ut on ct.camp_uid = ut.uid 
order by ot.id desc 
limit 2 
+0

感謝您的回覆沒有它不是我想要的,我想擁有每個客戶2條記錄,但今天的日期。這只是顯示2最後的記錄 –

1

按日期排序,並加入兩個表。

Select t1.camp_name, t2.uname,t3.message FROM order_table as t3 
    LEFT JOIN camp_table as t1 on t3.camp_id = t1.camp_id 
    LEFT JOIN user_table as t2 on t1.camp_uid = t2.uid 
    order by t3.orderDate desc 
    limit 2 
相關問題