臨時表:
group
sum int
lastid int
ids loooooongtext
phase int
初始化臨時表:
SET @SUM = 13;
INSERT INTO group
SELECT
tables.val AS sum,
tables.id AS lastid,
tables.id AS ids
0 AS phase
FROM tables
WHERE tables.val <= @SUM;
和一些環路(你可以使用PHP或MySQL做循環),半SQL,半僞代碼:
SET @PHASE = 0;
do
SET @PHASE = @PHASE + 1;
-- try to append new values to each group
INSERT INTO group
SELECT (group.sum + tables.val) AS sum,
tables.id AS lastid,
CONCAT(group.ids, ",", tables.id ) AS ids,
@PHASE AS phase
FROM group
INNER JOIN tables ON group.lastid < tables.id -- monotonity to prevent (some) duplicates
AND group.sum + tables.val <= @SUM;
-- delete dead ends
DELETE
FROM group
WHERE group.phase < @PHASE
AND group.sum != @SUM;
while ROW_COUNT() > 0;
如果循環準備就緒,從group
和group.ids
讀取每行將c繼續table.ids。
要獲得涉及2行以上的組合,您需要更多連接。更多... – 2012-02-18 21:46:07
感謝編輯即時通訊新的抱歉,你能給我一個例子嗎? – user2682025 2012-02-18 21:58:35
在SQL中執行這些置換,您將需要儘可能多的連接,因爲您需要總和中的操作數,其中每個連接都具有像't1.id!= t2.id AND t2.id!= t3.id AND t1的條件。 id!= t3.id'等等,它會很快變得無恥。 – 2012-02-18 22:02:02