如何将WHERE与JOIN LEFT一起使用?

时间:2017-02-10 16:11:15

标签: mysql

我有一个mysql请求,工作正常:

$pdo = $db->query('
SELECT *, 
GROUP_CONCAT(cat.name SEPARATOR " <br> ") AS dog, 
monkey.id AS id, 
duck.id AS horse_id, 
bird.id AS elephant_id
FROM monkey
LEFT JOIN duck ON monkey.horse=duck.id 
LEFT JOIN bird ON monkey.elephant=bird.id
LEFT JOIN cat ON monkey.id=cat.mouse_id 
GROUP BY monkey.id ASC;');

但现在我想只选择monkey =&#34; id&#34;。

的值

所以我尝试制作这个解决方案:

 $pdo = $db->query('
    SELECT *, 
    GROUP_CONCAT(cat.name SEPARATOR " <br> ") AS dog, 
    monkey.id AS id, 
    duck.id AS horse_id, 
    bird.id AS elephant_id
    FROM monkey WHERE id = "'.$id.'"
    LEFT JOIN duck ON monkey.horse=duck.id 
    LEFT JOIN bird ON monkey.elephant=bird.id
    LEFT JOIN cat ON monkey.id=cat.mouse_id 
    GROUP BY monkey.id ASC;');

但是我收到了这个错误:

  

致命错误:未捕获PDOException:SQLSTATE [42000]:语法错误或   访问冲突:1064您的SQL语法有错误;检查   手册,对应右边的MySQL服务器版本   要使用的语法附近&#39; LEFT JOIN duck on monkey.chorse = duck.id LEFT JOIN   鸟在猴子.bir&#39;在..mypage.php的第7行:28堆栈跟踪:#0   ..mypage.php(28):PDO-&gt;查询(&#39; \ nSELECT *,\ nGRO ...&#39;)#1 {main}抛出   在第28行的... mypage.php

2 个答案:

答案 0 :(得分:1)

首先,你必须制作where,然后制作 $pdo = $db->query(' SELECT *, GROUP_CONCAT(cat.name SEPARATOR " <br> ") AS dog, monkey.id AS id, duck.id AS horse_id, bird.id AS elephant_id FROM monkey LEFT JOIN duck ON monkey.horse=duck.id LEFT JOIN bird ON monkey.elephant=bird.id LEFT JOIN cat ON monkey.id=cat.mouse_id WHERE monkey.id = "'.$id.'" GROUP BY monkey.id ASC;'); ,试试这个:

helpDialog.open()

答案 1 :(得分:1)

所以,你有几个问题。首先,你没有清理你的id(查看Bobby Tables)。其次,您将WHERE子句放在错误的位置,第三,您不会告诉SQL使用哪个ID列。

将此作为一般模式:

SELECT
  <table1>.<column1>,
  <table2>.<column2>,
  (etc)
FROM
  <table1>
  JOIN
     <table>
     ON (<table1>.<id-column> = <table2>.<id-column)
WHERE
   <table1>.<id-column> = ${id-value}

在你的情况下,

$query = 'SELECT *, 
    GROUP_CONCAT(cat.name SEPARATOR " <br> ") AS dog, 
    monkey.id AS id, 
    duck.id AS horse_id, 
    bird.id AS elephant_id
FROM monkey 
    LEFT JOIN duck ON monkey.horse=duck.id 
    LEFT JOIN bird ON monkey.elephant=bird.id
    LEFT JOIN cat ON monkey.id=cat.mouse_id 
WHERE monkey.id = "'.$db->escape($id).'"
GROUP BY monkey.id ASC';