简体   繁体   English

MySQL:Select 行,其中字段包含唯一值

[英]MySQL: Select rows where field contains unique value

In MySQL database, I have a products table containing various product data, including company .在 MySQL 数据库中,我有一个包含各种产品数据的products表,包括company

id ID name姓名 company公司
1 1 Product 1产品一 AAA AAA
2 2 Another product另一种产品 BBB BBB
3 3 One more product又一款产品 CCC CCC
4 4 Item ZZZ项目 ZZZ BBB BBB
5 5 Product A产品A AAA AAA
6 6 Product uT产品 uT DDD DDD
7 7 Product 2z产品 2z AAA AAA

Now I want to build a query which will select all products which have a unique company - I mean a company, which appears only once in the whole table.现在我想建立一个查询,它将 select 所有具有唯一公司的产品 - 我的意思是一个公司,它在整个表中只出现一次。 In the above example - row 3 with company CCC and row 6 with company DDD.在上面的例子中——第 3 行是 CCC 公司,第 6 行是公司 DDD。

How can I achieve this?我怎样才能做到这一点?

You can use count(id) over(partition by company)您可以使用count(id) over(partition by company)

select id, name, company from
(select id, name, company , count(id) over(partition by company) cnt
from products) t
where cnt = 1;

Fiddle 小提琴

You can use GROUP BY... HAVING clause to find solo companies, then join to them by the company name.您可以使用 GROUP BY... HAVING 子句查找单独的公司,然后按公司名称加入它们。

SELECT * FROM products p
JOIN 
(SELECT company FROM products
GROUP BY company
HAVING COUNT(*) = 1) pg
ON p.company = pg.company

SQLFiddle here SQLFiddle在这里

MySQL will actually let you do this even simpler query. MySQL 实际上会让你做这个更简单的查询。 This works in this circumstance because there is only one row in the group you are looking for.这在这种情况下有效,因为您要查找的组中只有一行。 If however, you were looking for all the products for companies that have 2 products, the simpler version won't work anymore, as you'll only get one row back.但是,如果您正在为拥有 2 种产品的公司寻找所有产品,那么更简单的版本将不再适用,因为您只会得到一排。 The original query would continue to work with other HAVING clauses like HAVING COUNT(*) > 10原始查询将继续与其他 HAVING 子句一起使用,例如 HAVING COUNT(*) > 10

SELECT id, product, company
FROM products
GROUP BY company
HAVING COUNT(*) = 1

You need to group by company and then only select the rows that have one company:您需要按公司分组,然后仅 select 具有一家公司的行:

SELECT `id`, `name`, `company` FROM `products` GROUP BY `company` HAVING COUNT(*)=1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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