我知道为什么会出现这个错误,但我不知道如何解决。这是情况:
我有一个表 A,其中有下一列 userID
, switch
, plateType
, groupVal
, brokeage
.
userID
, plateType
和 groupVal
代表一个唯一的键。 groupVal
和 userId
可能有很多不同的值,但是 plateType
只能有 4(A,B,C,D)。
一个 userId
的记录示例和一个groupVal
将是:
Userid-------plateType------ groupVal------- brokeage
UserA--------- A----- ------------ 3--------------- 5.5
UserA--------- B----- ------------ 3--------------- 7.6
UserA--------- C----- ------------ 3--------------- 2.1
UserA--------- D----- ------------ 3--------------- 3.5
因此,当我运行下一个查询时,如果该记录不存在,则将被创建,但如果它们存在,则应该更新它们,但我得到的是这个错误:
Cardinality violation: 1242 Subquery returns more than 1 row
Insert into tableA (userID, plateType, groupVal, brokeage)
Select 'UserB', plateType, groupVal, brokeage from tableA
where userID = 'UserA'
on duplicate key
Update brokeage = (Select brokeage from tableA where userID = 'UserA')
我知道它在子查询中,我在更新中使用的选择...所以我真正需要的是从 tableA
中选择userId = UserA
所在的记录但这与 groupVal
匹配和 plateTypes
必须更新 UserB
.我希望我说清楚,有人可以给出答案。
最佳答案
您需要在 SELECT
语句中引用值,这意味着您根本不需要子查询。当我们引用 SELECT 中使用的表时,可以使用 UPDATE 中的值:
INSERT INTO tableA (userID, plateType, groupVal, brokeage)
SELECT 'UserB', plateType, groupVal, brokeage
FROM tableA AS t
WHERE userID = 'UserA'
ON DUPLICATE KEY
-- Set value of `brokeage` for UserB to the one set for UserA, from the SELECT
UPDATE brokeage = t.brokeage
关于mysql - 基数违规 : 1242 Subquery returns more than 1 row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21388667/