如何调试MySQL错误1242(子查询返回超过1行)?

时间:2012-09-11 09:20:05

标签: mysql debugging mysql-error-1242

有没有办法让MySQL在一个充满子查询的巨大自动生成查询中告诉哪个子查询给出了上述错误?如果没有,你的调试策略是什么?

2 个答案:

答案 0 :(得分:1)

我首先在查询和可能的子查询上使用LIMIT或DISTINCT。 如果这不起作用我会开始单独运行每个子查询,是的,这是耗时但我发现它也有助于避免将来出现同样的问题。

答案 1 :(得分:1)

示例查询:

UPDATE direct_orders do
SET do.dealer_id = (
    SELECT d.dealer_id FROM dealers d
    INNER JOIN dealer_addresses da 
        ON da.dealer_id = d.dealer_id
        AND da.type =  'M'
        AND da.status = 1
    INNER JOIN dealer_details dd 
        ON dd.dealer_id = d.dealer_id
        AND dd.status = 1
    WHERE ( da.address1 LIKE CONCAT(  '%', do.address1,  '%' ) AND do.postal LIKE da.postal_code ) 
    OR dd.name LIKE CONCAT(  '%', do.company,  '%' ) 
    AND do.dealer_id = 0
)

此查询失败,原因与海报相同。正确测试这种方法的一种方法是执行以下操作(请注意以前依赖于子关联的表的LEFT JOIN):

SELECT d.dealer_id FROM dealers d 
LEFT JOIN direct_orders do
    ON do.dealer_id = 0
INNER JOIN dealer_addresses da 
    ON da.dealer_id = d.dealer_id
    AND da.type =  'M'
    AND da.status = 1
INNER JOIN dealer_details dd 
    ON dd.dealer_id = d.dealer_id
    AND dd.status = 1
WHERE (da.address1 LIKE CONCAT(  '%', do.address1,  '%' ) AND do.postal LIKE da.postal_code ) 
OR dd.name LIKE CONCAT(  '%', do.company,  '%' )        

这样做表明事实上有一条来自" direct_orders"返回多个" dealer_id"来自"经销商"表。