3个表,左连接,以防在一个表中缺少DATA

时间:2011-02-07 12:39:32

标签: php mysql left-join

table1(ids始终存在)

+----+------+
| id | col1 |
+----+------+
| 1  |  ab  |
+----+------+
| 2  |  gh  |
+----+------+

table2(ids始终存在)

+----+------+
| id | col2 |
+----+------+
| 1  |  cd  |
+----+------+
| 2  |  ij  |
+----+------+

table3(可能缺少ID,在这种情况下 2 缺失)

+----+------+
| id | col3 |
+----+------+
| 1  |  ef  |
+----+------+

PHP

$col = 'ab';

$a = mysql_query("SELECT t1.id FROM table1 AS t1, table2 AS t2, table3 AS t3
WHERE t1.id = t2.id AND t2.id = t3.id AND (t1.col1 = '$col' OR t2.col2 = '$col'
OR t3.col3 = '$col) GROUP BY t1.id, t2.id, t3.id");

只有当所有三个表都包含“相同ID”时才会有效,但如果 table3 中出现“id”,会出于什么原因会发生什么?当 $ col = ab 时,我怎样才能测试所有三个表并获得t1.id输出1?我必须使用左连接吗?

$a = mysql_query("SELECT t1.id FROM table1 AS t1, table2 AS t2 
LEFT JOIN (SELECT id FROM table3 WHERE col3 = '$col') AS t3 ON t3.id = t1.id 
WHERE t1.id = t2.id AND (t1.col1 = '$col' OR t2.col2 = '$col')
GROUP BY t1.id, t2.id");

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

你做错了什么?查询不存在的表。这总是会引发错误。

我不打算解决设计数据库的智慧,在该数据库中,对您的查询至关重要的表来来去去。

客户方的唯一希望是

  • 测试表的存在 你感兴趣,
  • 执行不同的SQL语句 基于这些结果。

<小时/> [编辑后]

听起来你需要一个或两个左外连接。这将为您提供table1和table2共有的所有ID,无论它们是否在table3中。<​​/ p>

select t1.id, t2.id, t3.id
from table1 t1
inner join table2 t2 on (t1.id = t2.id)
left join table3 t3 on (t1.id = t3.id);

这将为你提供table1中的所有id,无论它们是在table2还是table3中。<​​/ p>

select t1.id, t2.id, t3.id
from table1 t1
left join table2 t2 on (t1.id = t2.id)
left join table3 t3 on (t1.id = t3.id);

当然,您可以使用WHERE子句过滤结果。

答案 1 :(得分:0)

LEFT JOIN仅在表存在时才有效,但不包含任何数据。

如果您不想执行Catcall suggested之类的操作(检查表是否存在,并使用基于该表的不同SQL语句...),您必须确保该表存在于数据库,即使它完全是空的。

在正常情况下,您应该对应用程序的数据库有一定程度的控制权,因此您应该能够确保表格确实在那里。

如果这确实是一个大问题(例如,您无法确定是否有人删除了表格),您可以在每次启动应用程序时进行检查:如果表格不存在则创建表格。