PHP / MySQL - 选择字段唯一的所有行

时间:2012-06-13 17:41:21

标签: php mysql select unique

我有一张这样的表:

column_a  column_b
  foo        1
  bar        1
  bar        2
  baz        4

我希望得到以下结果,包含所有行,column_b中具有唯一字段值:

  bar        2
  baz        4

foo(0)和bar(1)都有column_b值'1',因此'1'不是唯一的。 是否有MySQL-Expression过滤所有具有唯一column_b

的行

也许是这样的:

select * from table where isunique(column_b)

另外:我不需要像DISTINCT那样的东西!

编辑(已解决):

感谢YaK和jcho360,这个是解决方案:

select column_a, column_b from table group by column_b having count(column_b) = 1

OR

select column_a, column_b, COUNT(1) AS total from table group by column_b having total = 1

(thx to andrewtweber)

3 个答案:

答案 0 :(得分:4)

使用count函数将提供一个选择,其中column_b中的值仅出现一次。试试这个:

select * from table group by (column_b) having count(column_b) = 1;

答案 1 :(得分:3)

SELECT column_a, column_b, COUNT(1) AS total
FROM table
GROUP BY column_b
HAVING total = 1

我认为应该有效。这会将所有column_b组合在一起并计算有多少具有该特定值,然后将结果集限制为具有唯一column_b值的那些。

答案 2 :(得分:-1)

请尝试select unique(column_b), column_a, from table? :)

编辑修复错误

相关问题