我目前有一个非常简单的MySQL查询,如下所示:
SET @recordID = 60749; SELECT netID, ID, recordID, team FROM NetLog WHERE recordID = @recordID;
变量recordID对于每一行都是唯一的,并且是获取所需行的唯一可用变量。
但是现在我还需要返回具有与原始行相同的'team'值的任何其他行。我尝试了几种变化,但它总是返回“#1242 - 子查询返回多于1行”。
SET @recordID = 60749; SELECT a.netID, a.ID, a.recordID, a.team, (SELECT b.recordID FROM NetLog b WHERE b.team = a.team AND b.recordID <> a.recordID) as rID FROM NetLog a WHERE a.recordID = @recordID;
如果可能的话,我希望在一次查询中完成这个操作。
有人可以指点我正确的方向吗?
P粉3788901062023-09-14 11:42:17
使用UNION
来组合查询。
WITH mainRow AS ( SELECT netID, ID, recordID, team FROM NetLog WHERE recordID = @recordID ) SELECT * FROM mainRow UNION SELECT b.netID, b.ID, b.recordID, b.team FROM NetLog AS b JOIN mainRow AS a ON b.team = a.team AND b.recordID <> a.recordID