[英]MySQL Select from 3 tables where multiple conditions
我從3個MySQL表中選擇數據時遇到問題。
我想顯示以下列:
SELECT table1.id as UserID, table1.gender, table1.land, table1.dob, table1.category_id, table1.is_participant, table2.*
我想要使用的條件是:
WHERE table1.id = table2.user_id
OR table3.id = table2.responder_id
所以我想要使用的整個查詢是:
SELECT table1.id as UserID, table1.gender, table1.land, table1.dob, table1.category_id, table1.is_participant, table2.*
FROM table1, table2, table3
WHERE table1.id = table2.user_id
OR table3.id = table2.responder_id
這個查詢有什么問題? 出於某種原因,每次我詢問此查詢時,該過程永遠不會結束。
謝謝你的幫助!
Never ends意味着查詢synthax是正確的並且由引擎正確解析,但執行速度很慢。 你在那張桌子里有多少數據?
看一下該表上的索引和數據結構優化。 但是請嘗試以這種方式使用JOIN:
SELECT table1.id as UserID, table1.gender, table1.land, table1.dob, table1.category_id, table1.is_participant, table2.*
FROM table1
JOIN table2 ON table1.id = table2.user_id
JOIN table3 ON table3.id = table2.responder_id
我建議明確使用連接:
FROM table2
LEFT JOIN table1 ON table1.id = table2.user_id
LEFT JOIN table3 ON table3.id = table2.responder_id
WHERE table1.id IS NOT NULL OR table3.id IS NOT NULL;
由於你有OR
操作數,你需要在這里使用LEFT JOIN
:這樣你將擁有所有表中的記錄,然后對它們執行WHERE ... OR
。
導師制加入這里
使用此代碼:
SELECT
table1.id as UserID,
table1.gender,
table1.land,
table1.dob,
table1.category_id,
table1.is_participant,
table2.*,
table3.* // you not mention the table3 field, i just mention the all fields
FROM table1
join table2
on table1.id = table2.user_id
join table3
on table3.id = table2.responder_id
注意: 我有一個疑問,你使用table3
但沒有提到field name
。
你的問題很模糊,先說出你想要達到的目的。 我認為你的查詢是錯誤的,因為你已經添加了很多時間,因為你已經添加了OR條件。
當您編寫FROM table1,table2,table3時,這意味着MySql必須創建一個臨時表,該表將包含所有三個表中所有行的所有排列。 這就是為什么你通過添加適當的WHERE條件來限制MySql必須進行排列的數量。
我認為你需要添加AND條件而不是OR。
如果想要更快的結果,還要確保將table1.id,table2.user_id,table3.id和table2.responder_id編入索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.