2016-07-26 68 views
2

請轉換以下查詢爲連接查詢而不使用子查詢在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 

回答

1

一種方式端口查詢到一個連接將左連接user_registration使用子查詢在followers。要保留的記錄標準是用戶註冊標識不是'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 
+0

找到空記錄。 –

+0

@AnkitVirani對不起,我遺漏了'ON'子句。你能再試一次嗎? –

+0

感謝您對我們的幫助:) –

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' 
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; 
+0

此查詢使用舊式ANSI-92之前的語法,這被很多人視爲不鼓勵。 –

+0

相應編輯 – DharmasriS

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以查看正在使用哪些索引。

+0

感謝您對我們的幫助:) –

+0

如何在PhpMyadmin中啓用EXPLAIN? –