简体   繁体   中英

MySQL Select from 3 tables where multiple conditions

I have a problem selecting data from 3 MySQL tables.

I want to show the following columns:

SELECT table1.id as UserID, table1.gender, table1.land, table1.dob, table1.category_id, table1.is_participant, table2.*

The condition I want to use is:

WHERE table1.id = table2.user_id
OR table3.id = table2.responder_id

So the entire query I am trying to use is:

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

What is wrong with this query? For some reason, every time I ask this query, the process never ends.

Thanks for your help!

Never ends means that the query synthax is right and correctly parsed by the engine, but the execution is slow . How much data do you have in that table ?

Take a look at indexes on that table and on the data structure optimization. However try using a JOIN in this way :

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

I suggest using joins explicitly:

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;

Since you have OR operand you need to use LEFT JOIN here: this way you'll have records from all the tables, and then perform WHERE ... OR on them.

Tutorial on joins here

use this code:

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

Note: I had an one doubt, your using the the table3 but not mention the field name .

Your question is vague, first tell what you are trying to achieve. I think your query is wrong, by the way its taking alot of time because of OR condition that you have added.

When you write FROM table1, table2, table3 it means MySql has to create a temporary table which will contain all permutations of all the rows in all three tables. Thats why you limit number of permutations that MySql has to make by adding proper WHERE condition.

I think you need to add AND condition instead of OR.

Also make sure table1.id, table2.user_id, table3.id and table2.responder_id are indexed if you want faster result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM