Select name, lastname, brand from table where brand is the most voted

Viewed 58

I have this select

SELECT firstname, lastname, email, brand
FROM (SELECT brand, COUNT(brand) AS choiced 
FROM users 
GROUP BY brand  
ORDER BY `choiced` DESC
LIMIT 1) AS winner
ORDER BY RAND()
LIMIT 1

Error #1054 column firstname in field set is unknow.

I have table users, with columns id, firstname, lastname, email and brand I need to select one (and only one) random user (firstname, lastname, email) from the users that selected the most voted brand.

So if I make:

SELECT brand, count(brand) AS choiced 
FROM users 
GROUP BY brand 
ORDER BY choiced DESC LIMIT 1

Result is: brand JOE DOE, Choiced 47.

But I don't know how to obteined the random user inside those 47 users.

I hope that I explained myself, English is not my first language.

3 Answers

If there will be one brand with a maximum number of votes you may try the following:

SELECT id, firstname, lastname, email, brand
  FROM users 
  WHERE brand = (
                 SELECT brand FROM users
                 GROUP BY brand ORDER BY COUNT(*) DESC LIMIT 1
                )
ORDER BY RAND()
LIMIT 1;

If it could be more than one brand that have the max number of votes then you may try the following:

SELECT id, firstname, lastname, email, brand
  FROM users 
  WHERE brand IN (
                 SELECT brand FROM users GROUP BY brand
                 HAVING COUNT(*) = (
                                    SELECT COUNT(*) FROM users
                                    GROUP BY brand ORDER BY COUNT(*) DESC LIMIT 1
                                   )
                )
ORDER BY RAND()
LIMIT 1;

See a demo.

SELECT firstname, lastname, email, brand,choiced 
FROM (SELECT firstname, lastname, email, brand, COUNT(brand) AS choiced 
FROM users 
GROUP BY brand  
ORDER BY COUNT(brand) DESC
LIMIT 1) AS winner
ORDER BY choiced 
SELECT users.*
  -- subquery 1 - calculate the max rows amount per brand
FROM ( SELECT COUNT(*) max_count
       FROM users
       GROUP BY brand
       ORDER BY 1 DESC LIMIT 1 ) max_count
  -- subquery 2 - get brands list with the max rows amount
JOIN ( SELECT brand, COUNT(*) max_count
       FROM users
       GROUP BY 1 ) max_count_brand USING (max_count)
  -- join users of the brands above
JOIN users USING (brand)
  -- get one random user
ORDER BY RAND() LIMIT 1;
Related