我有以下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
結果應該是最近日期的價格,小於每個項目的用戶輸入日期。 如何實現這一目標?
這_is_你得到的結果fiddle here。你的意思是它應該只是最近的價格,在你搜索的日期之前? –
'ORDER BY e_date DESC LIMIT 1'? – RST
是pala_,它必須是用戶搜索日期前的最近價格 –