簡體   English   中英

如何從MySQL查詢中的每個項目獲取一行

[英]How to get one row per each item from and mysql query

我有以下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

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

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

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

小提琴在這里顯示了所需的行為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM