$stmt = $con->prepare("SELECT t.name, COUNT(*)
FROM team t
JOIN member m ON FIND_IN_SET( m.team_id, t.id ) >0
GROUP BY t.name
LIMIT 0 , 30");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('count', $count);
$stmt->bindColumn('name', $name);
while ($row = $stmt->fetch())
{
echo "<tr><td>".$name."</td>";
echo "<td>".$count."</td>";
}
上面的代码检索了2列:name和count(*)
。问题在于访问计数列;我得到以下错误。
警告:PDOStatement :: bindColumn():SQLSTATE [HY000]:常规错误:未找到列名&#39; count&#39;在定义的列中;它不会受到约束
我如何绑定到总计数?
答案 0 :(得分:4)
使用别名:COUNT(*) as count
。
$stmt = $con->prepare("SELECT t.name, COUNT(*) as count
FROM team t
JOIN member m ON FIND_IN_SET( m.team_id, t.id ) >0
GROUP BY t.name
LIMIT 0 , 30");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('count', $count);
$stmt->bindColumn('name', $name);
while ($row = $stmt->fetch())
{
echo "<tr><td>".$name."</td>";
echo "<td>".$count."</td>";
}
答案 1 :(得分:1)
您可以指定列号(从1开始),而不是使用具有列名的别名。
$stmt = $con->prepare("SELECT t.name, COUNT(*)
FROM team t
JOIN member m ON FIND_IN_SET( m.team_id, t.id ) >0
GROUP BY t.name
LIMIT 0 , 30");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn(2, $count);
$stmt->bindColumn(1, $name);