2015-05-07 132 views
0

我有兩個表格,舊格式和新格式的用戶。我想將舊格式的用戶與單獨的表格進行匹配,然後排除也顯示在新用戶格式表格中的所有用戶。我的數據是這樣的:選擇MYSQL結果,其中表1和2匹配,2和3不匹配

Table newUsers: 
+----+-------+-------+----------+ 
| id | oldid | first | last  | 
+----+-------+-------+----------+ 
| 1 | 10 | John | Kennedy | 
| 2 | 66 | Mitch | Kupchak | 
+----+-------+-------+----------+ 

Table posts: 
+----+---------+ 
| id | user_id | 
+----+---------+ 
| 1 |  10 | 
| 1 |  66 | 
| 1 |  88 | 
| 2 |  88 | 
| 2 |  28 | 
| 3 |  10 | 
+----+---------+ 

Table oldUsers: 
+----+----------+-------+----------+ 
| id | username | first | last  | 
+----+----------+-------+----------+ 
| 10 |  A | John | Kennedy | 
| 66 |  B | Mitch | Kupchak | 
| 88 |  C | Dale | Earnhardt| 
+----+----------+-------+----------+ 

Result wantend: 
+----+----------+-------+----------+ 
| id | username | first | last  | 
+----+----------+-------+----------+ 
| 88 |  C | Dale | Earnhardt| 
+----+----------+-------+----------+ 

我想通過指定選擇我的結果:posts.id = 1和posts.user_id = oldUsers.id和newUsers.oldid = oldUsers.id所以我只收到oldUser .id等於88,因爲他不在新用戶列表中。

我試過各種JOINS和SUBQUERIES。我不斷收到newUsers表中的所有結果,而不是結果減去相應的條目。

回答

0

這裏是一個辦法做到這一點

select 
o.* from oldUsers o 
left join newUsers n on o.id = n.oldid 
left join posts p on n.oldid = p.user_id or o.id = p.user_id 
where n.id is null and p.id= 1; 

爲了獲得更好的性能添加以下指標

alter table newUsers add index oldid_idx(oldid); 
alter table posts add index user_post_idx (id,user_id); 
+0

這工作,但花了3.5秒,當做解釋說,它說創造了第一個左連接噸行。所以使用效率太低。 –

+0

你需要索引到表中,我已經添加了表可能需要的索引。我假設來自olduser和newuser的id都是主鍵,因此不需要在它們上應用額外的索引。 –

+0

添加了它們,它確實將它平均降到了0.023。但是我自己的代碼仍然執行速度提高了5.22倍。 –

0
select * from oldusers where id in 

select * from 

(select id from oldusers where id in 
select distinct userid from posts where id=1) 
where id not in (select oldid from newusers); 
+0

這是格式錯誤的代碼。 –

+0

它的工作原理,它爲什麼畸形? – DCR

+0

#1064 - 你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,選擇正確的語法以在'select * from (從oldusers中選擇id,在 中的id選擇第3行中的disti' –

0

我最終找到我對我自己的答案,然後來到這裏找到其他人試過。 Abhik的代碼確實有效,但效率太低而無法使用。我結束了我自己的代碼玩,直到我發現了更有效的東西。

select o.* from posts p, oldUsers o 
LEFT JOIN newUsers n ON o.id = n.oldid 
WHERE p.user_id = o.id AND p.id = 1 AND n.id IS NULL 

執行時間爲0.0044秒。我可以在生產網站上使用的東西。

隨着從以前的答案添加索引,它現在執行.001x秒,所以一定要用我自己的代碼。