简体   繁体   中英

Get rows having same column value

I have a following table where I need to find the maximum consumers of a company. I have a users table and a company table.A users can use many products of a different companies and a company can have many users as its consumers. user_id is a foreign key used in this table from users table and company_id is a foreign_key used from company table

TABLE consumers_company

Suppose we have the following data:-

 user_id | company_id 
---------------------
   6     |    1      
   6     |    2      
   7     |    5       
   8     |    8      
   8     |    1
   8     |    8          

Now as we can see company 1 has maximum users.I am using this query to find those companies which have users more than 1.

SELECT *
FROM consumers_company
WHERE company_id IN (
SELECT company_id
FROM consumers_company
GROUP BY company_id
HAVING COUNT(company_id) > 1)

My Output:-

user_id | company_id
--------------------
 6      |  1
 8      |  8        
 8      |  1         
 8      |  8                 

Required Output:-

user_id | company_id
--------------------
 6      |  1
 8      |  1         

I am a beginner in MySQL.Please help me out.

select * from consumers_company where company_id in 
(select company_id from consumers_company group by company_id
order by count(distinct user_id) desc limit 1)

First find out the company which have the most unique user_id relation in the consumers_company table.And the give out all its consumers.

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