查询加入同一个表3次


Query joining the same table 3 times

我创建了一个在phpMyAdmin中运行良好的查询,但当我试图在.php文件中调用它时,我会收到以下错误。

Undefined variable: mothers_name in C:'wamp'www'Family_Tree'showfamily.php on line 56

我的代码是:

$select_query = "SELECT a.id, CONCAT( a.surname,  ', ', a.first_names ) AS child_name, " . 
"CONCAT( b.surname,  ', ', b.first_names ) AS mothers_name, " .
"CONCAT( c.surname, ', ', c.first_names ) AS fathers_name " .
"FROM family_members a " .
"INNER JOIN family_members b ON a.mother_id = b.id " .
"INNER JOIN family_members c ON a.father_id = c.id" .
"WHERE a.id = " . $user_id;

我收到这个错误是因为表"a"、"b"answers"c"以及字段"mother_id"answers"parent_id"在通过mysql_query($select_query)函数调用SQL之前不存在。

第56行之前的代码查找、返回并显示结果。

..._id = c.id" .               // <-- you forgot a space, results in c.idWHERE
"WHERE a.id = " . $user_id;

如果你从java风格的换行中退一步,这样攻击它,你可能会发现这一切都会容易得多。PHP中不需要将其拆分,而且额外的标点符号更容易出错。

$select_query = 
"SELECT 
     a.id, 
     CONCAT( a.surname, ', ', a.first_names ) AS child_name, 
     CONCAT( b.surname, ', ', b.first_names ) AS mothers_name,
     CONCAT( c.surname, ', ', c.first_names ) AS fathers_name 
FROM family_members a 
INNER JOIN family_members b ON a.mother_id = b.id 
INNER JOIN family_members c ON a.father_id = c.id
WHERE a.id = " . $user_id;

这将允许您使用非常方便的调试工具:

echo "[pre]" . $query . "[/pre]";

而[&]实际上是<amp;>。抱歉,SO 新手

然后,您可以将浏览器窗口中的实际查询复制/粘贴到phpMyAdmin中,然后运行该查询,看看它们是否真的相同。