查询以获取大多数获胜用户

时间:2016-09-27 03:21:47

标签: php mysql

我有两个表电影和用户,我使用此查询来获取获胜者的用户

$winners_query=("Select * from users where user_id IN (Select user_id from film where iswinningclip=1) order by user_id desc limit 12"); 

我很难编写一个查询来对数据进行排序,以便大多数时候赢得胜利的用户应该首先出现,等等。

这对我不起作用

$winners_query=("Select * from users where user_id IN (Select count(user_id) AS CN from film where iswinningclip=1 oder by CN desc) order by user_id desc limit 12"); 

users表包含user_id和其他相关字段,电影表包含film_id,user_id,iswinningclip 有人可以建议我吗。

谢谢

4 个答案:

答案 0 :(得分:0)

首先选择userid和iswinningclip,然后按用户ID应用分组,这样你就可以得到iswinningclip的总数,然后对该列应用max function。那是谁赢了。

答案 1 :(得分:0)

在这种情况下您可以使用联接,否则您使用的查询看起来更复杂

SELECT  users.*, film.*
FROM  users 
inner join
film  
On (users.id = film.user_id)
WHERE film.iswinningclip = 1
Group by users.id
Order by count(users.id) DESC

答案 2 :(得分:0)

在user_id上使用两个表的连接,将条件赋予winsclip = 1,按用户ID应用组,最后根据user_ids的数量按降序排序结果

查询应该像

SELECT 
    u.id, u.username, u.gender //select as many columns you want from users
FROM
    users u
        JOIN
    film f ON (u.id = f.user_id)
WHERE
    f.iswinningclip = 1
GROUP BY u.id
ORDER BY COUNT(u.id) DESC

完整示例

CREATE TABLE users (
  id INT NOT NULL AUTO_INCREMENT,
  username VARCHAR(45) NULL,
  gender VARCHAR(45) NULL,
  PRIMARY KEY (id));

CREATE TABLE film (
  id INT NOT NULL AUTO_INCREMENT,
  user_id INT NULL,
  film_id INT NULL,
  iswinningclip INT NULL,
  PRIMARY KEY (id));


INSERT INTO users (username, gender) VALUES ('Kiran', 'M');
INSERT INTO users (username, gender) VALUES ('Liza', 'F');
INSERT INTO users (username, gender) VALUES ('Ajith', 'M');

INSERT INTO  film (film_id, user_id, iswinningclip) VALUES ('1', '1', '1');
INSERT INTO  film (film_id, user_id, iswinningclip) VALUES ('1', '2', '1');
INSERT INTO  film (film_id, user_id, iswinningclip) VALUES ('2', '1', '0');
INSERT INTO  film (film_id, user_id, iswinningclip) VALUES ('2', '2', '1');
INSERT INTO  film (film_id, user_id, iswinningclip) VALUES ('3', '3', '1');

SELECT 
    u.id, u.username, u.gender
FROM
    users u
        JOIN
    film f ON (u.id = f.user_id)
WHERE
    f.iswinningclip = 1
GROUP BY u.id
ORDER BY COUNT(u.id) DESC

结果

enter image description here

答案 3 :(得分:0)

试试这个会对你有所帮助。

SELECT  users.*, count(film.user_id) as no_of_awards
FROM  users join film  
On (users.user_id = film.user_id)
WHERE film.iswinningclip = 1
Group by users.user_id
Order by no_of_awards DESC