即使使用DISTINCT,SQL SELECT查询也会回显两次

时间:2013-01-21 17:49:39

标签: php mysql sql select

我在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 个答案:

答案 0 :(得分: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 tableSELECT a,b FROM table GROUP BY a,b

的工作方式相同

请关注文档:

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

答案 2 :(得分:0)

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

所以你永远不会得到

Col1  Col2
A     B
A     B

但你可以得到

Col1  Col2
A     B
A     C

答案 3 :(得分:0)

尝试:

SELECT `title`, group_concat(distinct `extra_fields_search`)
FROM `blahblah_items` 
WHERE catid=336 
Group BY `title`
ORDER BY 2