2011-06-27 100 views
0

我有下面的代码。它工作,如果我只使用一个WHERE变量,但现在我添加另一个,查询不起作用。联盟有两个约束?

它的工作原理,如果我只用这一个所有的工会:

 where table_constant.user_id = '$uid' 

但是,当我在下面用这一个,这是行不通的:

 where table_constant.user_id = '$uid' and table_one.something <> '$uid' 

代码:

$sql = "select table_one.field1, table_constant.field1, 
table_one.field2, table_one.field3, table_one.field4, 
table_one.field5, table_constant.c_id 
from table_one LEFT JOIN table_constant on table_one.field1 
= table_constant.c_id 
where table_constant.user_id = '$uid' and table_one.something <> '$uid' 
UNION 
select table_two.field1, table_constant.field1, table_two.field2, 
table_two.field3, table_two.field4, table_two.field5, table_constant.c_id 
from table_two LEFT JOIN table_constant on table_two.c_id 
= table_constant.c_id 
where table_two.added_by = '$uid' and table_two.something <> '$uid' 
UNION 
select table_three.field1, table_constant.field1, table_three.field2, 
table_three.field3, table_three.field4, table_three.field5, 
table_constant.c_id 
from table_three LEFT JOIN table_constant ON table_three.c_id 
= table_constant.c_id 
where table_constant.user_id = '$uid' and table_three.something <> '$uid' 
UNION 
select table_four.field1, table_constant.field1, table_four.field2, 
table_four.field3, table_four.field4, table_four.field5, 
table_constant.c_id 
from table_four LEFT JOIN table_constant ON table_four.c_id 
= table_constant.c_id 
where table_constant.user_id = '$uid' and table_four.something <> '$uid' 
ORDER BY date DESC LIMIT $start, $limit"; 
$result = mysql_query($sql); 
+0

你是什么意思的“不工作”?结果是什么? – Dan

+0

它不显示任何内容。 – KPO

+0

然后我想你将不得不展示一些应该给出结果但没有结果的数据。 – idstam

回答

1

一想到我对这个问题可能会有一个不错的猜测。当你写一个LEFT JOIN时,我认为你这样做是因为可能有一些行与连接右侧的任何内容不匹配。如果您想约束那些确实以某种方式匹配的行,则需要在JOIN本身中执行此操作。例如:

LEFT JOIN table_constant ON table_one.field1 = table_constant.c_id AND table_constant.user_id = '$uid' 

通过将第二个条件的WHERE子句中,你实际上把左连接到内通过强制右侧有一个值加入。