2017-02-10 67 views
0

我有一個MySQL的要求,那是工作的罰款:我如何使用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 
GROUP BY monkey.id ASC;'); 

但現在我想選擇其中猴=「ID」僅值。

所以我試圖使這個解決方案:

$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;'); 

但我得到這個錯誤:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN duck ON monkey.chorse=duck.id LEFT JOIN bird ON monkey.bir' at line 7 in ..mypage.php:28 Stack trace: #0 ..mypage.php(28): PDO->query('\nSELECT *, \nGRO...') #1 {main} thrown in ...mypage.php on line 28

+2

如有疑問,請檢查[語法](https://dev.mysql.com/doc/ refman/5.5/EN/select.html)。 select語句有一個特定的順序。 – aynber

回答

1

首先,你必須使joins,然後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;'); 
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'; 
+0

我不知道'db-> escape'是否是你需要的,但你需要逃避那個瓦里。 – cwallenpoole

+0

它沒有很好地逃脫工作! – Jarla

+1

@Jarla問題是,如果沒有轉義,您可能會遇到SQL注入。我建議你看看它。 – cwallenpoole