MySQL如何在连接中使用相关查询

时间:2013-11-22 14:39:30

标签: mysql sql join left-join correlated-subquery

我发现,MySql不支持连接中的相关查询。是否有可能重写提供的(简单的)查询保持逻辑?

SELECT *
FROM tableX AS x
LEFT JOIN ( 
    SELECT y.xFK, COUNT(y.id) AS y_count
    FROM tableY AS y
    WHERE y.xFK = x.id
    GROUP BY y.xFK
) AS sub
ON sub.xFK = x.id
WHERE sub.y_count > 1

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

SELECT
  x.*, COUNT(y.ID) AS y_count
FROM tableX x
  LEFT JOIN tableY y
    ON y.xFK = x.ID
GROUP BY
  x.ID
HAVING
  y_count > 1