INNER JOIN:where子句太含糊不清

时间:2013-05-30 07:14:48

标签: php mysql

我收到错误"Integrity constraint violation: 1052 Column 'restaurant_id' in where clause is ambiguous' in"

a)如何在JOIN上使用bindparam?这甚至是造成这个错误的问题吗?

function restaurant(PDO $dbh, $username) {
   global $dbh;
   $stmt = $dbh->prepare("
      SELECT        *
      FROM          users u
      INNER JOIN    menues m
      ON            u.user_id = m.restaurant_id
      INNER JOIN    users_slider s
      ON            m.restaurant_id = s.restaurant_id
      WHERE         restaurant_id = :restaurant_id
   ");

   $stmt->bindParam(":restaurant_id", $_GET['r']);
   $stmt->execute();
   return $stmt->fetchAll();
}

4 个答案:

答案 0 :(得分:10)

更改

...
WHERE     restaurant_id = :restaurant_id

...
WHERE     m.restaurant_id = :restaurant_id
          ^^

答案 1 :(得分:2)

请根据您的表格使用m.restaurant_ids.restaurant_id条件来解决您的问题。

答案 2 :(得分:2)

始终使用别名来避免连接查询中的冲突。此处restaurant_id应为m.restaurant_id

尝试此查询: -

SELECT        *
      FROM          users u
      INNER JOIN    menues m
      ON            u.user_id = m.restaurant_id
      INNER JOIN    users_slider s
      ON            m.restaurant_id = s.restaurant_id
      WHERE         m.restaurant_id =:restaurant_id

答案 3 :(得分:1)

放在像WHERE m.restaurant_id =:restaurant_id

这样的条件
function restaurant(PDO $dbh, $username) {
   global $dbh;
   $stmt = $dbh->prepare("
      SELECT        *
      FROM      users u
      INNER JOIN    menues m
      ON            u.user_id = m.restaurant_id
      INNER JOIN    users_slider s
      ON            m.restaurant_id = s.restaurant_id
      WHERE     m.restaurant_id = :restaurant_id
   ");

   $stmt->bindParam(":restaurant_id", $_GET['r']);
   $stmt->execute();
   return $stmt->fetchAll();
}