2015-06-01 65 views
1

我有以下MySQL表:如何從獲得每個每個項目一個行和MySQL查詢

---+-------+------------+---------- 
id | price | e_date | item_name 
---+-------+------------+---------- 
1 | 1000 | 2015-01-01 | pen 
2 | 1050 | 2015-02-01 | pen 
3 | 850 | 2015-03-01 | pen 
4 | 800 | 2015-03-20 | pen 
5 | 1150 | 2015-04-01 | pen 
6 | 750 | 2015-02-01 | pencil 
7 | 900 | 2015-03-01 | pencil 
8 | 950 | 2015-03-15 | pencil 
---+-------+------------+---------- 

如果我查詢表:

"SELECT item_name,price as p,e_date FROM test_table WHERE (item_name='pen' or item_name='pencil') AND e_date<='$e_date'" 
//(*Here $e_date gets from user input) 

取出的結果如下:

Price of pen is 1000 on 2015-01-01 against user input: 2015-03-01 
Price of pen is 1050 on 2015-02-01 against user input: 2015-03-01 
Price of pen is 850 on 2015-03-01 against user input: 2015-03-01 
Price of pencil is 750 on 2015-02-01 against user input: 2015-03-01 
Price of pencil is 900 on 2015-03-01 against user input: 2015-03-01 

但我想結果將包含每個item_name只有一行像:

Price of pen is 850 on 2015-03-01 against user input: 2015-03-01 
Price of pencil is 900 on 2015-03-01 against user input: 2015-03-01 

結果應該是最近日期的價格,小於每個項目的用戶輸入日期。 如何實現這一目標?

+0

這_is_你得到的結果fiddle here。你的意思是它應該只是最近的價格,在你搜索的日期之前? –

+0

'ORDER BY e_date DESC LIMIT 1'? – RST

+0

是pala_,它必須是用戶搜索日期前的最近價格 –

回答

2

首先,您需要確定最近的日期,比您的搜索查詢早。每件。

select item_name, max(e_date) e_date 
    from test_table 
    where e_date < '$e_date' 
    group by item_name 

我們再加入針對此查詢檢索結果的其餘部分:

select t.* 
    from test_table t 
    inner join (
    select item_name, max(e_date) e_date 
     from test_table 
     where e_date < '$e_date' 
     group by item_name 
    ) q 
    on t.item_name = q.item_name 
     and t.e_date = q.e_date 

是顯示期望的行爲

+0

Thankyou非常pala_,這是我想要的輸出。感謝您昨天的努力,以解決我的問題。 –

+1

@ AbdullahMamun-Ur-Rashid在小提琴中使用2015-03-01不會返回您指定的結果。不應該代碼查找'<='而不是'<' – RST

+0

是的,我已經更正了該代碼。此外,如果我使用WHERE item_name = pen OR item_name = pencil和.......等等之前的項目(假設有25000個item_name),我可以限制搜索項目之間的e_date <='$ e_date'爲有限數量的項目。這將減少查詢時間。但pala_向我展示了指南。 –

相關問題