请在不使用mysql中的子查询
的情况下将以下查询转换为连接查询SELECT u.id, u.name, u.avatar, u.slug, u.location
FROM user_registration as u
WHERE u.id <>'3' AND u.id NOT IN (SELECT f.user_id FROM followers as f WHERE f.follower_id ='3')
order by id
答案 0 :(得分:1)
将查询移植到联接的一种方法是在user_registration
上使用子查询离开加入followers
。要保留的记录的条件是用户注册ID不是'3'
,并且该记录与followers
上的子查询的连接中的任何内容都不匹配。
SELECT t1.id, t1.name, t1.avatar, t1.slug, t1.location
FROM user_registration t1
LEFT JOIN
(
SELECT f.user_id
FROM followers f
WHERE f.follower_id = '3'
) t2
ON t1.id = t2.user_id
WHERE t1.id <> '3' AND t2.user_id IS NULL
ORDER BY t1.id
我认为以下查询也应该有效:
SELECT t1.id, t1.name, t1.avatar, t1.slug, t1.location
FROM user_registration t1
LEFT JOIN followers t2
ON t1.id = t2.user_id AND t2.follower_id = '3'
WHERE t1.id <> '3' AND t2.user_id IS NULL
ORDER BY t1.id
答案 1 :(得分:1)
这是一个不使用子选择的连接查询:
SELECT
u.id, u.name, u.avatar, u.slug, u.location
FROM
user_registration u
LEFT JOIN followers f ON (u.id = f.user_id AND f.follower_id = 3)
WHERE
u.id <>'3' AND
f.user_id IS NULL
ORDER BY id
请注意,如果您使用子选择(如少数其他答案),即使您正在加入其结果,MySQL仍可能使用内部临时表(缺少任何索引)来执行连接。如果您加入实际表,则保留使用现有索引加入的所有好处。您始终可以运行EXPLAIN
以查看正在使用的索引。
答案 2 :(得分:0)
SELECT u.id, u.name, u.avatar, u.slug, u.location
FROM user_registration as u
LEFT JOIN followers ON followers.follower._id = u.id
AND u.id <>'3'
答案 3 :(得分:0)
这可能有效
SELECT u.id, u.name, u.avatar, u.slug, u.location
FROM user_registration u LEFT JOIN followers f
ON u.id=f.user_id
WHERE u.id <>'3' AND f.follower_id <>'3'
order by u.id;