2014-03-31 118 views
0

从3个MySQL表中选择数据时遇到问题。MySQL从3个表中选择多个条件

我想说明以下栏目:

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 

这个查询有什么问题?出于某种原因,每次我询问这个​​查询时,这个过程都不​​会结束。

感谢您的帮助!

+0

您可以添加sqlfiddle.com中的表和数据,并在您的问题的预期结果。 –

+0

抱歉,我们不能,这是属于我工作的公司的私人信息 – Alberto

+2

@AhhikChakraborty表示示例数据。不是实际的数据:) –

回答

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

1

从不结束意味着查询合成器是正确的并且被引擎正确解析,但执行速度很慢。你在该表中有多少数据?

查看该表上的索引和数据结构优化。然而尝试使用这样一个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 
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

+0

看看我的答案,同时,有一个疑问,你使用'table3'但没有提及'field name'。 – jmail

0

你的问题含糊不清,首先告诉你想要达到的目标。我认为你的查询是错误的,顺便说一下,由于你添加了OR条件,它会花费很多时间。

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

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

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