带有存在子查询的MySQL左连接返回的行数多于应该的数量

时间:2017-07-18 11:10:38

标签: mysql sql database

我有一个MySQL数据库和带有子查询的SQL查询。

我100%确定表s_k_p只有一行s_k_p.season_id = 2s_k_p.user_id = k_i.user_id

无论如何,问题是LEFT JOIN s_k_p AS skp2部分返回10行。如上所述,它应该只返回一行。

SELECT skp2.season_id AS invalid_status_id
FROM comp_i
  INNER JOIN k_i ON k_i.ilmo_id = comp_i.id

  LEFT JOIN s_k_p
    ON s_k_p.user_id = k_i.user_id
       AND s_k_p.season_id = 4

  LEFT JOIN s_k_p AS skp2
    ON skp2.user_id = k_i.user_id
       AND EXISTS (
         SELECT *
           FROM s_k_p
           WHERE s_k_p.season_id = 2
             AND s_k_p.user_id = k_i.user_id
       )
WHERE comp_i.comp_id = ?
ORDER BY k_i.id ASC

表s_k_p具有以下行:

season_id | user_id
1 | 25
1 | 459
2 | 459
3 | 459
3 | 9999
4 | 459
4 | 758

第二行是唯一一个s_k_p.season_id = 2s_k_p.user_id = k_i.user_id应该为真的行。

1 个答案:

答案 0 :(得分:1)

如果在S_K_P表中有10行用于返回10行,则查询可能正确,因为这是左连接。

你有一个SECONDARY级别存在于同一个S_K_P表,但包含Season_ID = 2.

如果你关心的只是同一个用户存在,第2季,那么改为

 LEFT JOIN s_k_p AS skp2
    ON skp2.user_id = k_i.user_id
    AND skp2.season_id = 2