0

以下にこのコードがあります。1 つの 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);
4

1 に答える 1

1

よく考えてみると、問題が何であるかについて、かなりの推測ができます。LEFT JOIN を記述するときは、結合の右側に一致しない行がいくつかある可能性があるため、そうすると思います。何らかの方法で一致する行を制限したい場合は、JOINそれ自体で行う必要があります。例えば:

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

句に 2 番目の条件を配置するWHEREことで、右側に値を強制することで、本質的に左側の結合を内部結合に変えています。

于 2011-06-27T04:48:19.310 に答える