选择不同组的不同值

时间:2013-09-11 04:12:49

标签: php mysql performance multidimensional-array distinct

我有一张类似的表:

    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..

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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']);
}