我有一个包含一些值的表,如下所示,我想得出一些值,主题的总和等于另一个值,让我们说像13:
id values
1 4
2 7
3 5
4 6
我想得出那些等于13的值。 朋友给了我一个查询:
SELECT t1.* FROM tables AS t1
INNER JOIN tables AS t2
WHERE t1.id != t2.id AND t1.`values` + t2.`values` = 13
但它返回的只有两个值,但是假设我想要两个以上的值,甚至更多 4 + 7 + 5 = 16或4 + 7 + 5 + 6 = 22 我的意思在这里我不想只有两个数字,有时我需要更多,这取决于我想要的价值。请给我一个解决方案。
答案 0 :(得分:0)
临时表:
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
将包含table.ids。