2

我有一个类似的表:

    id  title  year
    ---------------
    1    abc   1999
    2    abc   2000
    3    abc   2000
    4    abc   1998
    5    bce   1999
    6    bce   1999
    7    def   1999
    8    def   1999
    9    def   2000

我正在尝试获得一个类似于

array('abc' => 'array(1999,2000,1998)', 'bce' => 'array(1999)', 'def' => 'array(1999, 2000)');

我知道很长的路要走,我认为它很耗时:

PHP:
$rid = mysql_query("SELECT DISTINCT title from table_name ORDER BY ASC);
while($arr = mysql_fetch_array($qr)){
   $title = $arr
   $rid = mysql_query("SELECT DISTINCT title from table_name ORDER BY ASC);
   $yearArr = array();
   while($arr2 = mysql_fetch_array($qr)){
      $yearArr[] = $arr2['year'];
   }
   $finalArr = array(title => $yearArr);
}

最后我得到了我正在寻找的数组,但是从上面的代码中,如果我有 1000 个不同的标题,那么整个过程将执行 1001 个查询。有没有什么捷径可以做到这一点?

我还找到了一个类似的,但我无法更进一步:

SELECT DISTINCT year,title FROM table_name WHERE title IN (SELECT DISTINCT title FROM papers_scanned_01) ORDER BY title ASC, year DESC

使用上面的查询我得到一个数组如下

array( [0] => 'abc', [1] => '1999', [2] => '2000', [3] => '1998', [4] => 'bce' and so on..
4

2 回答 2

1

在函数中使用DISTINCT关键字group_concat()来获取不同的值。

像这样修改您的查询 -

SELECT title, group_concat(DISTINCT year) as years
FROM tb1
group by title

小提琴 - http://www.sqlfiddle.com/#!2/0812a/4

输出-

TITLE   YEARS
abc     1999,2000,1998
bce     1999
def     1999,2000
于 2013-09-11T04:48:37.823 回答
0

您可以使用以下代码获得所需的数组,只需执行 1 个 SQL

$sql = "SELECT title, group_concat(year) as years FROM table_name group by title"
$rs = mysql_query($sql);
$arr = array();
while($row = mysql_fetch_assoc($rs)) {
   $arr[$row['title']] = explode(',',$row['years']);
}
于 2013-09-11T04:21:10.030 回答