如何在查询中进行子选择?

时间:2018-02-12 11:31:01

标签: php mysql select

像这样我的查询工作正常:

$pdo = $db->prepare('SELECT *
    FROM projects WHERE project_id = :project_id ');  
    $pdo->execute(array('project_id' => $project_id));
    while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
         echo "ok";
}

但是当我添加一个子选择时,我得到一个空白页面:

$pdo = $db->prepare('SELECT *
    (SELECT * FROM animals WHERE projects.animal=animals.id) AS animal
    FROM projects WHERE project_id = :project_id ');  
    $pdo->execute(array('project_id' => $project_id));
    while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
         echo "ok";
}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以使用INNER JOIN同时拥有两个表。

$pdo = $db->prepare('SELECT *
FROM projects
INNER JOIN animals ON projects.animal=animals.id
WHERE project_id = :project_id ');  
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
   echo "ok";
}

尝试此查询,因为此查询将返回所有具有动物关联动物的项目。

我认为这是你想要的

答案 1 :(得分:0)

找到了这个解决方案:

$pdo = $db->prepare('SELECT *
    FROM projects 
    LEFT JOIN animals ON projects.animal=animals.id
    WHERE project_id = :project_id ');  
    $pdo->execute(array('project_id' => $project_id));
    while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
         echo "ok";
}