有一个数据库的表table1结构和部分数据如下
这里的id-是主键,自动,aid-是另外一个表的主键,name-是值
id   aid  name
1     2     是
2     1     阿
3     1     什么
4     1     是
5     3     阿
6     2     什
7     4     好
8     4     是
...我想实现的是,列出这些数据,相同的name的只显示一次,并在这些name后面标出有多少条数据,这些数据的aid分别是什么,最后的效果name    数量     aid
是        3       1 2 4
阿        2       1 3
什么      1       1
什        1       2
好        1       4请问这个用php该如何写出来呢?数据库是mysql数据库

解决方案 »

  1.   

    $sql = 'select name, count(id) as num from table group by name';
    DBConnection();//此处连数据库(mysql_connect)
    $ret = mysql_query($sql);
    $arr = array();
    while($row = mysql_fetch_assoc($ret)){
    $sql = 'select aid from table where name = "'.$row['name'].'"';
    $res = mysql_query($sql);
    $s = '';
    while($res = mysql_fetch_assoc($res)){
    $s .= $res['aid'].' ';
    }
    $row['the_aid'] = $s;
    $arr[] = $row;
    }
    echo '<pre>';print_r($arr);
      

  2.   

    分两布吧  先取出 是这个字的数量 select count(*) as num,name from table group by name
    然后用name 去找aid select aid from table where name='$name'
      

  3.   

    aid是字符串型肯定没问题,  aid如果只显示一次如下即可,如果都列出了,取消DISTINCT 
    SELECT name, GROUP_CONCAT( DISTINCT aid
    SEPARATOR " " ), count( * ) AS num
    FROM table1 
    GROUP BY name
      

  4.   

    经测试,整型也可以,
    SELECT name, GROUP_CONCAT( DISTINCT aid
    SEPARATOR " " ) AS aid, count( * ) AS num
    FROM table1 
    GROUP BY name
      

  5.   

    +好语句,sql我是很菜啊客气了,我想写的让你写了。一起学习啊