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

Issue

This Content is from Stack Overflow. Question asked by Leandro Severino

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.



Solution

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.


This Question was asked in StackOverflow by Leandro Severino and Answered by Ahmed It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?