簡體   English   中英

從mysql中選擇幾行並指定一列的總和

[英]Selecting several rows from mysql with specified total sum of one column

我有2張桌子

item_info

ID | Name       | Price
---+------------+-------
1  | Item one   | 0.2
2  | Item two   | 0.3
3  | Item three | 0.1
4  | Item four  | 0.6

item_list

ID | item_id | available
---+---------+----------
1  |       1 | 1
2  |       3 | 1
3  |       2 | 1
4  |       1 | 1
5  |       4 | 1
etc..

我需要選擇任何數量從表item_list其在塔的價格總和加入了與表item_info從表中的行的item_info = 0.6 $

例如,它可以選擇item_list.item_id = 1,2,3的3行或item_list.item_id 4的一行-不管但結果總和不超過0.6 $

我也只需要選擇item_list.available = 1個項目,然后將它們標記為不可用

我嘗試了一些請求,但實際上沒有任何用處

我需要類似的東西

select item_list.ID, item_info.Name 
from item_list
inner join item_info on item_info.ID=item_list.item_id
where item_list.available = 1  
  and total sum of rows item_info.price <= 0.6

我試圖使用變量

select @sum:=0;
select *,@sum:=@sum+price as total_sum from (
  select item_list.ID,item_info.price from item_list
    inner join item_info on item_info.ID=item_list.item_id
    where item_list.available=1 
  order by price asc
) s
having total_sum<=0.6

但是它不是最好的方法,是從最便宜的到最貴的中選擇商品,而且它之前也會讀取整張桌子。

該邏輯相對簡單,但是,無論它變得多么復雜,都無法在單個查詢中實現。 顯然,您可以在mysql中使用存儲過程來實現邏輯,也可以使用php。

  1. 計算項目,這些價格小於或等於您的限制。 如果該值為0,則說明您沒有合格項目,或者列表已准備就緒-請參閱下面的步驟3。
  2. 通過生成一個介於0和count-1之間的隨機整數並將其用於limit語句中,以其價格檢索1個價格小於或等於您的限制的隨機項目:

    select itemid, price from table order by itemid limit randomnumber, 1

  3. 從限額中扣除價格。 如果您的剩余限制為0,則您有自己的清單。 如果不是,請重復上述步驟,將剩余限制變為新限制。 如果您不想在列表中兩次包含相同的項目,那么在重復上述步驟時,可以通過在where子句中添加一個not in()來排除列表中的項目ID。

暫無
暫無

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

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