[英]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 ![]() |
name![]() |
company![]() |
---|---|---|
1 ![]() |
Product 1![]() |
AAA ![]() |
2 ![]() |
Another product![]() |
BBB ![]() |
3 ![]() |
One more product![]() |
CCC ![]() |
4 ![]() |
Item ZZZ![]() |
BBB ![]() |
5 ![]() |
Product A![]() |
AAA ![]() |
6 ![]() |
Product uT![]() |
DDD ![]() |
7 ![]() |
Product 2z![]() |
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 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
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.