计算表中的实例并捕获每个实例的id

时间:2013-08-13 00:58:04

标签: php mysql sql pdo count

我要做的是搜索我的表并计算一个字母的实例,并将每个实例的ID存储在mysql和php(PDO)中。

我一直在搞乱的是:

$user = 'john';
$stmt = $pdo->prepare("SELECT id, SUBSTR(surname, 1, 1) as surname_init,COUNT(*) as count FROM first_table WHERE user = :user GROUP BY surname_init ORDER BY count DESC");
$stmt->bindValue(":user", $user);

$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

var_dump($row);

结果如下:

array (size=2)
  0 => 
    array (size=3)
      'id' => string '3' (length=1)
      'surname_init' => string 'B' (length=1)
      'count' => string '2' (length=1)
  1 => 
    array (size=3)
      'id' => string '7' (length=1)
      'surname_init' => string 'D' (length=1)
      'count' => string '1' (length=1)

所以我有两个结果:B有2个实例,D有一个。但是“B”只有一个从两个返回的结果id。

这可能吗?我想我在这里错过了什么..

2 个答案:

答案 0 :(得分:3)

使用GROUP_CONCAT()获取与该组匹配的所有行,例如:

SELECT
    GROUP_CONCAT(id) AS id_list,
    SUBSTR(surname, 1, 1) as surname_init,
    COUNT(*) as count
FROM first_table
WHERE user = :user
GROUP BY surname_init
ORDER BY count DESC

答案 1 :(得分:0)

看看这是否有帮助:

$user = 'john';
// use this to get unique starting characters for surnames for the user John
$stmt = $pdo->prepare("SELECT SUBSTR(surname, 1, 1) as `surname_init`, 
                       COUNT(*) as `count` FROM first_table 
                       WHERE user = :user GROUP BY 
                       surname_init ORDER BY count DESC");
$stmt->bindValue(":user", $user);
$stmt->execute();
$rows1 = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows1 as $row1){
    echo "<BR>Starting Letter: " . $row1['surname_init'];
    echo "<BR>Count: " . $row1['count'];

    // now get all the IDs for this user that have the 
    // surnames starting with this alphabet
    $stmt = $pdo->prepare("SELECT ID, SUBSTR(surname, 1, 1) as `surname_init`, 
                       FROM first_table 
                       WHERE user = :user 
                       AND surname LIKE :surname");
    $stmt->bindValue(":user", $user);
    $stmt->bindValue(":surname", $row1['surname_init']."%");

    $stmt->execute();
    $rows2 = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows2 as $row2){
        // do insert based on ID here
    }        
}