使用LIMIT和ORDER选择多个表行

时间:2017-08-25 20:12:59

标签: php mysql sql pdo

我有4张这样的表

  table0plus                 table10plus                    table20plus
[id  -   name ]              [id -  name ]               [id  -  name  -  age]
[1   -  garick]              [1  -  nizak]               [1  -  karin  -  25 ]
[2   -  garry ]              [2  -  nimar]               [2  -  kuster -  28 ]

    tabletype
[ name    -   type  ]
[ garry   -   male  ]
[ nizak   -  female ]
[ karin   -  female ]
[ nimar   -   male  ]

我试图从所有表中选择所有值,而我尝试的是

$query = "
SELECT a.id, a.name, b.type, '-20' AS age FROM table0plus a LEFT JOIN tabletype b ON a.name = b.name WHERE id = :id
UNION ALL
SELECT a.id, a.name, b.type, '-10' AS age FROM table10plus a LEFT JOIN tabletype b ON a.name = b.name WHERE id = :id
UNION ALL
SELECT a.id, a.name, b.type, a.age FROM table20plus a LEFT JOIN tabletype b ON a.name = b.name WHERE id = :id
ORDER BY age
LIMIT :limit
";

但它不会起作用并给我一个错误。

我试图输出date or name or age排序的值并且全部受限。我怎么能正确地做到这一点?

错误是

Fatal error
: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number

我的PDO代码是

$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $conn->prepare($query);
$stmt->execute(['id' => $id, 'limit' => $limit]);

尝试执行'id' => $id 3次,但问题仍然存在。

0 个答案:

没有答案