我有以下表结构:
+------+-------+-------+--------+ | mid | a | b | points | +------+-------+-------+--------+ | 69 | 3137 | 13316 | 210 | | 70 | 13316 | 3137 | 350 | | 71 | 3497 | 13316 | 200 | | 72 | 13316 | 3497 | 25 | | 73 | 3605 | 13316 | 205 | | 74 | 13316 | 3605 | 290 | +------+-------+-------+--------+
我想在行1的“a”=第2行的“b”和第2行的“a”=第1行的“b”时添加两行的“points”值。
输出必须是这样的:
+------+-------+-------+--------+ | mid | a | b | points | +------+-------+-------+--------+ | 69 | 3137 | 13316 | 560 | | 71 | 3497 | 13316 | 225 | | 73 | 3605 | 13316 | 495 | +------+-------+-------+--------+
答案 0 :(得分:0)
如果我理解正确,那么你想要:
SELECT p1.mid, p1.a, p1.b, p1.points + p2.points points
FROM points p1
INNER JOIN points p2 ON p1.a = p2.b AND p1.b = p2.a
WHERE p1.mid < p2.mid
我已在sql fiddle中将其删除并提供您想要的输出。
答案 1 :(得分:0)
你可以这样试试
SELECT t1.mid, t1.a, t1.b, t1.points + t2.points points
FROM table1 t1 JOIN table1 t2
ON t1.a = t2.b
AND t1.b = t2.a
AND t1.mid < t2.mid
或利用MySQL非标准GROUP BY
扩展名
SELECT mid, a, b, SUM(points) points
FROM
(
SELECT mid, a, b, points
FROM table1
ORDER BY mid
) q
GROUP BY LEAST(a, b), GREATEST(a, b)
输出:
| MID | A | B | POINTS | |-----|------|-------|--------| | 69 | 3137 | 13316 | 560 | | 71 | 3497 | 13316 | 225 | | 73 | 3605 | 13316 | 495 |
这是 SQLFiddle 演示