选择所有列WHERE一列不是DISTINCT

时间:2015-02-06 20:51:46

标签: mysql

我有一张包含id,名称,价格和人员参数的表格。我只需要选择所有不同的,但id总是不同的,这使我的目标复杂化(我使用id只是为了处理动态页面)所以我需要选择除id 之外的所有参数。我希望我有道理。有办法解决这个问题吗?

非常感谢。

例如:

ID | NAME | PRICE | PEOPLE
1  | beef |  9    |   2
2  | beef |  5    |   1
3  | beef |  9    |   2
4  | pork |  6    |   1 

Result:

ID | NAME | PRICE | PEOPLE
1  | beef |  9    |   2
2  | beef |  5    |   1
4  | pork |  6    |   1 

我已经解决了这个问题。这是查询:

SELECT every.name, every.price, every.people, every.id 
FROM 
(SELECT * FROM sometable) AS every 
INNER JOIN 
(SELECT DISTINCT name, price, people FROM sometable) AS unique 
ON (every.name = unique.name AND every.price=unique.price AND every.people=unique.people);

1 个答案:

答案 0 :(得分:1)

您可以从同一个表创建两个数据集(uniqall)并加入这些数据集。您只会从uniq获取不同的行。因此,您可以确保对于all中与所有三个属性匹配的任何条目,只有一个可能的ID。

SELECT * FROM 
(SELECT id, name, price, people FROM sometable) as all
INNER JOIN (SELECT DISTINCT(name, people, price) FROM sometable) as uniq  ON
(all.name = uniq.name AND all.price = uniq.price AND all.people = uniq.people) ;