我目前有一個非常簡單的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