在JOINed表上MySQL / PDO语法不正确

时间:2015-01-12 10:43:16

标签: php mysql sql join pdo

我正在尝试使用1个select语句从2个表中检索数据。

测试一次失败

$sql = "SELECT banned FROM users WHERE id =:id UNION SELECT first_name, last_name, 
mobile_phone,email, city, address, postal_code, user_type, 
active FROM personal WHERE id =:id";

我从这次尝试中了解到,您无法选择不同数量的列,甚至可以使其工作。

尝试两次失败

$sql = "SELECT users.banned, personal.first_name, personal.last_name, personal.mobile_phone,
personal.email, personal.city, personal.address, personal.postal_code, personal.user_type,
personal.active FROM users WHERE users.id =:id INNER JOIN personal WHERE personal.id =:id";

得到了这个: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 'INNER JOIN personal WHERE personal.id ='21'

尝试按别名选择失败

上次尝试失败

$sql = "SELECT banned, first_name, last_name, mobile_phone, email, city, address, postal_code, user_type, active FROM users WHERE users.id =:id INNER JOIN personal WHERE personal.id =:id";

缺少想法或尝试做错事。

1 个答案:

答案 0 :(得分:1)

您的语法和逻辑不正确:

SELECT u.banned
     , p.first_name
     , p.last_name
     , p.mobile_phone
     , p.email
     , p.city
     , p.address
     , p.postal_code
     , p.user_type
     , p.active 
FROM users u JOIN  personal p ON u.id = p.id
WHERE u.id =:id

一些提示:

  • 当您使用UNIONUNION ALL时,您应该记住,所涉及的所有SELECT应该具有相同数量的字段。
  • WHERE始终追踪FROMJOIN ON条款。