说我有一张桌子,如下:
| id | value |
--------------
| 1 | 6 |
| 4 | 12 |
我想返回加起来等于一定值的两行
例如我想得到2行,总数为18,因此在上表中它应该返回:
SELECT *, (t1.value+t2.value) AS total
FROM test t1, test t2
WHERE t1.id != t2.id
HAVING total = 18
LIMIT 1
...因为此处的值之和为18,所以其他3行即使它们加起来也不应匹配,因为在这种情况下,它只能是2行之和。
此外,如果有多对加起来等于所需值,则它应仅返回第一个匹配项。
编辑:
跟上这个似乎可以解决问题,但我不确定这是最好的方法
{{1}}
答案 0 :(得分:0)
MySQL并不真正适合此类查询。我能想到的唯一[令人敬畏的]解决方案是对表进行自我联接以获取两条记录,然后将该联接放入CTE中并使用union all
来将两条记录分别放在单独的行上: / p>
WITH summer AS (
SELECT a.id AS a_id, a.value AS a_value, b.id AS b_id, b.value AS b_value
FROM mytable a
JOIN mytable b ON a.id <> b.id AND a.value + b.value = 18
ORDER BY a.id, b.id
LIMIT 1
)
SELECT a_id, a_value
FROM summer
UNION ALL
SELECT b_id, b_value
FROM summer
答案 1 :(得分:0)
这与您所追求的类似...
SELECT x.id x_id
, y.id y_id
FROM my_table x
JOIN my_table y
ON y.id > x.id
WHERE x.value + y.value = 18
ORDER
BY x.id
, y.id
LIMIT 1;
答案 2 :(得分:0)
以下是执行此操作的简单查询:
SELECT
number1.id, number2.id
FROM
number AS number1
JOIN
number AS number2 ON number1.value + number2.value = 18
AND number2.id > number1.id