0

我正在 PHP 中创建一个简单的 SQL 查询 - 出于某种原因,即使DISTINCT使用它,它也会像这样显示两次:

BC
BC
OH
OH
TX
TX

这是我的代码:

<?php
$sql = "SELECT DISTINCT `title`,`extra_fields_search` FROM `blahblah_items` WHERE catid=336 ORDER BY `blahblah_items`.`extra_fields_search` ASC ";
$partnerlisting= mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($partnerlisting))
foreach($row as $cname => $cvalue){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;

?>

我怎样才能使它只打印出一个?

4

4 回答 4

1
SELECT 
    `title`,
    `extra_fields_search` 
FROM 
    `blahblah_items` 
WHERE 
    catid=336 
GROUP BY 
    SUBSTRING(extra_fields_search,1,2) # here. group by first two characters of extra_fields_search
    # or just "GROUP BY extra_fields_search", depends what you need
ORDER BY 
    `blahblah_items`.`extra_fields_search` ASC

SELECT DISTINCT a,b FROM table工作方式与SELECT a,b FROM table GROUP BY a,b

请遵循文档:

于 2013-01-21T17:51:43.370 回答
0

试试这个

SELECT `title`,`extra_fields_search` 
FROM `blahblah_items` WHERE catid=336 
Group BY extra_fields_search
ORDER BY `blahblah_items`.`extra_fields_search` ASC

编辑:在你的代码中试试这个

    while($row = mysql_fetch_assoc($partnerlisting))
    $rows[] = $row;
    foreach($rows as $row){
    echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
    }
   ;
于 2013-01-21T17:54:36.503 回答
0

Distinct 确保您获得唯一的行。它不能确保您将获得唯一的列值。在您的情况下,如果您考虑结果中的所有字段,您会注意到每一行与另一行至少有一个字段不同。

所以你永远不会得到

Col1  Col2
A     B
A     B

但是你可以得到

Col1  Col2
A     B
A     C
于 2013-01-21T17:54:51.447 回答
0

尝试:

SELECT `title`, group_concat(distinct `extra_fields_search`)
FROM `blahblah_items` 
WHERE catid=336 
Group BY `title`
ORDER BY 2
于 2013-01-21T17:57:40.153 回答