2013-03-27 81 views
1

运行此查询,选择从数据库中唯一记录

select * from table; 

返回以下

|branch | number | 
------------------- 
| 1 | 123 | 
| 1 | 001 | 
| 2 | 123 | 
| 3 | 123 | 
| 4 | 123 | 
| 1 | 123 | 
| 1 | 789 | 
| 2 | 123 | 
| 3 | 123 | 
| 4 | 009 | 

我想找到所独有的唯一分支机构值1

| 1 | 001 | 
| 1 | 789 | 

可以这样没有将数据存储在单独的表中?我试过几个“select distinct”查询&似乎没有得到我期待的结果。

回答

1

我猜我想说的是,我想找到所有仅适用于分支1的数字。如果它们在任何其他分支中找到,我不想看到它们。

我想这就是你想要的。

SELECT distinct number 
FROM MyTable 
WHERE branch=1 and number not in 
(SELECT distinct number 
FROM MyTable 
WHERE branch != 1) 
+0

非常感谢!这看起来像它正是我所需要的。 – webhead74 2013-03-27 19:48:15

0

试试这个:

SELECT branch, number 
FROM table 
GROUP BY branch, number 

这里是一个SQLFiddle让你看看

如果你想将其限制在只有1处,则只需添加一个WHERE子句。

SELECT branch, number 
FROM table 
WHERE branch = 1 
GROUP BY branch, number 
2
SELECT branch, number 
FROM table 
WHERE branch = 1 
GROUP BY branch, number 
2

如果您不需要任何聚集,可以使用distinct代替group by

select distinct branch 
,  number 
from YourTable 
where branch = 1 
+0

谢谢,但是这不是我正在寻找的东西。运行该查询将返回可能在其他分支中找到的“数字”列值。我想我想说的是,我想查找所有只有分支1唯一的数字。如果他们在任何其他分支中找到,我不想看到它们。 – webhead74 2013-03-27 19:15:34

0

要选择在number列独特的全值,并有1 branch值,可以使用下面的代码:

SELECT branch, number 
FROM table1 
WHERE number IN (
SELECT number 
FROM table1 
GROUP BY number 
HAVING (COUNT(number) = 1) 
) 
AND branch = 1 

对于一个演示中看到http://sqlfiddle.com/#!2/97145/62