简体   繁体   中英

Records with Unique (Not Distinct) values in mySQL

I would like to have to know which of my users has a UNIQUE OS on their machine

I am not interested in anyone who is not totally unique. (we are looking for the lone wolves here) I am not looking for Distinct values. Just the records that are totally unique.

Here is the SQL

CREATE  TABLE `Computers` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `CPU` VARCHAR(45) NULL ,
  `OS` VARCHAR(45) NULL ,
  PRIMARY KEY (`ID`) );


INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('386', 'win 3.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('486', 'Dr Doss');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('286', 'win 3.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('68000', 'Mac OS 7.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('68030', 'Mac OS 7.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('Z80', 'CPM');

Given this data I should get back only the following rows:

ID       OS
2        Dr Doss
6        CPM

Can someone help me with the SQL statement?

Use a GROUP BY clause with HAVING COUNT() .

SELECT ID, OS
FROM Computers
GROUP BY OS
HAVING COUNT(OS) = 1;

The GROUP BY clause narrows it down to one row per OS and the HAVING clause filters out OS 's that have multiple rows in the table.

http://sqlfiddle.com/#!2/cbfc2/11

use having example provided above

select min(`id`), `os`, count(*) as total
from computers
group by `os`
having `total` = 1

This?

SELECT * FROM computers
GROUP BY OS
HAVING COUNT(ID) = 1

SQL FIDDLE TEST

SELECT *
FROM computers
INNER JOIN
(
SELECT OS, COUNT(*) AS OsCount
FROM computers
GROUP BY OS
HAVING OsCount = 1
) Sub1
ON computers.OS = Sub1.OS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM