【问题标题】:Cardinality violation: 1242 Subquery returns more than 1 row基数违规:1242 子查询返回多于 1 行
【发布时间】:2014-01-27 18:26:16
【问题描述】:

我知道这个错误的原因,但我不知道如何解决它。情况如下: 我有一个 tableA,其中包含下一列 userIDswitchplateTypegroupValbrokeageuserIDplateTypegroupVal 代表唯一的密钥。 groupValuserId 可能有许多不同的值,但 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

因此,当我运行下一个查询时,如果此记录不存在,则将创建该记录,但如果它们存在,则应该对其进行更新,但是我得到的是这个错误:

基数违规:1242 子查询返回多于 1 行

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 和@ 匹配的记录987654339@ 必须更新为 UserB。我希望我说清楚,有人可以给出答案。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您需要引用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 
    

    【讨论】:

    • 这种方法的问题在于它会更新,但都具有相同的值。例如果userA在plateType D中有3.5个breakage,则brpokeage中UserB的所有行都取这个值。
    • 重新阅读您的问题,您甚至根本不需要子查询,请参阅我的编辑。
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 2012-09-17
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2018-08-06
    相关资源
    最近更新 更多