MySQL从3个表中选择多个条件

时间:2014-03-31 10:29:21

标签: mysql

我在从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

此查询有什么问题?出于某种原因,每次我询问此查询时,该过程永远不会结束。

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我建议明确使用联接:

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

关于联接的教程here

答案 2 :(得分:0)

使用此代码:

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

答案 3 :(得分:0)

你的问题很模糊,先说出你想要达到的目标。我认为你的查询是错误的,因为你已经添加了很多时间,因为你已经添加了OR条件。

当您编写FROM table1,table2,table3时,这意味着MySql必须创建一个临时表,该表将包含所有三个表中所有行的所有排列。这就是为什么你通过添加适当的WHERE条件来限制MySql必须进行排列的数量。

我认为您需要添加AND条件而不是OR。

还要确保 如果你想要更快的结果,table1.id,table2.user_id,table3.id和table2.responder_id被编入索引。

相关问题