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

MySQL / PDO syntax incorrect on JOINed tables

我正在尝试使用 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";

我从这次尝试中了解到,你不能有不同数量的列 selected 它们需要均匀才能工作。

尝试两次失败

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

已尝试 select使用别名失败

最后一次尝试也失败了

$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";

运行 不知道还有什么可以尝试或我做错了什么。

您的语法和逻辑不正确:

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 总是在带有 ON 子句的 FROMJOIN 之后。