1

我正在尝试使用连接启动子选择,但返回时遇到问题

SELECT * FROM user, follow
WHERE user.id IN ( SELECT follow FROM referent_follow WHERE referent=3 )

在上述情况下,回报很好,但我还拥有我不想要的所有表格

SELECT * FROM user, follow
WHERE follow.user_id IN ( SELECT follow FROM referent_follow WHERE referent=3 )

在上述情况下,回报很好,但我还有所有我不想要的表用户

效果不太好的查询是第一个,但我的结果中也有后续内容。

4

2 回答 2

1

FROM A,B表示 A 和 B 的交叉连接。因此 A 中的每一行都与 B 的每一行匹配
(so totalRows = rowCount(A)*rowCount(B))。

使用(INNER) JOIN应该工作:

SELECT *
FROM user
JOIN follow ON user.id = follow.user_id
  AND user.id IN ( SELECT follow FROM referent_follow WHERE referent=3 )

建议使用JOIN而不是IN,因为它通常会带来更好的性能:

SELECT user.*, follow.*
FROM user
JOIN follow ON user.id = follow.user_id
JOIN referent_follow ON user.id = referent_follow.follow
WHERE referent=3

您可能还需要DISTINCTJW 建议的。

于 2013-03-30T10:19:17.740 回答
1

Your current query result a cartesian product from both tables: user and follow. You need to supply a condition that will join and filter out connected records.

SELECT  DISTINCT a.*, b.* 
FROM    user a
        INNER JOIN follow b
            ON a.ID = b.user_id 
        INNER JOIN referent_follow c
            ON a.ID = c.follow
WHERE   c.referent = 3
于 2013-03-30T10:19:44.207 回答