如何在获得非重复条目时查询重复条目?

时间:2018-04-03 15:09:31

标签: php mysql

我有一张这样的桌子..:

Table

我试图弄清楚如何只查询其中一个重复的条目,同时仍然获得非重复的条目?

$query = "SELECT id, size, color FROM `".$item."` WHERE size in (SELECT size FROM `".$item."`
                GROUP BY size HAVING COUNT(*)>1)";
$resul = $conn->query ($query);
if($resul->num_rows > 0){
    while($r = $resul->fetch_assoc()){
        echo $r["size"];
    }
}

2 个答案:

答案 0 :(得分:0)

SQL DEMO

这会为每个尺寸选择ID最大的行:

SELECT t1.id, t1.size, t1.color 
FROM yourTable t1
LEFT JOIN yourTable t2
  ON t1.id < t2.id
 and t1.size = t2.size
WHERE t2.id IS NULL   // if no one is bigger than you, you are the biggest.

现在你过滤一行多了一行

 AND t1.size ( SELECT size
               FROM yourTable
               GROUP BY size
               HAVING count(*) > 1)

答案 1 :(得分:0)

您可以这样查询:

SELECT size, color, quantity FROM `yourtable` group by size

但是,它会显示与 Small 相关的第一行,如下所示:

query result