[英]Select name, lastname, brand from table where brand is the most voted
I have this select我有这个 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.错误 #1054 字段集中的列名未知。
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.我有表用户,列 id、firstname、lastname、email 和我需要的品牌 select 一个(也是唯一一个)随机用户(名字、姓氏、电子邮件)来自选择投票最多的品牌的用户。
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.结果是:品牌 JOE DOE,Choiced 47。
But I don't know how to obteined the random user inside those 47 users.但我不知道如何获得这 47 个用户中的随机用户。
I hope that I explained myself, English is not my first language.我希望我自己解释一下,英语不是我的第一语言。
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;
SELECT firstname, lastname, email, brand,choiced FROM (SELECT firstname, lastname, email, brand, COUNT(brand) AS choiced FROM users GROUP BY brand SELECT firstname, lastname, email, brand,choiced FROM (SELECT firstname, lastname, Z0C83F57C786A0B4A39EFABGROUP23731C7EBCZ, brand, COUNT(brand) 用户选择 BY
ORDER BY COUNT(brand) DESC LIMIT 1) AS winner ORDER BY choiced ORDER BY COUNT(brand) DESC LIMIT 1) 作为获胜者 ORDER BY selected
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.