简体   繁体   English

MySql-在一个查询中从两个不同的表中选择用户名

[英]MySql - Select user name from two different tables in one query

I have 3 tables 我有3张桌子

  • users table with user name and user id, 用户表,其中包含用户名和用户ID,
  • leader board of users with user id and score 具有用户ID和得分的用户排行榜
  • leader board of likes with user id and numOfLikes 用户ID为numOfLikes的点赞排行榜

I want to select the name of the user with the most likes, and the name of the users with the most score. 我想选择最喜欢的用户的名称和得分最高的用户的名称。 But my problem is that when I am writing the query I have duplicated name field there. 但是我的问题是,当我编写查询时,我在那里重复了name字段。 What should I do? 我该怎么办?

using alias may help you 使用别名可能会帮助您

SELECT a.id as id_a,
  b.id as id_b,
  c.id as id_c
from a
inner join b
  on a.id = b.a_id
inner join c
  on a.id = c.a_id

You are probably using SELECT * . 您可能正在使用SELECT * You should specify the field names: 您应该指定字段名称:

SELECT u.user_id, u.name, li.numOfLikes FROM users u INNER JOIN likes li ON (u.user_id=li.user_id) ORDER BY li.numOfLikes

SELECT u.user_id, u.name, s.score FROM users INNER JOIN scores s ON (u.user_id=s.user_id) ORDER BY s.score

i use following three tables in my query 我在查询中使用以下三个表

  1. usertable - contain username and userid usertable-包含用户名和用户ID
  2. table2 - contain userid and score table2-包含用户标识和分数
  3. table3 - contain userid and numOfLikes table3-包含userid和numOfLikes

To get details of user with max score use following 要获取具有最高分数的用户的详细信息,请使用以下

select usrtbl.username,usrtbl.userid,tbl2.score from  usertable usrtbl inner join table2 tbl2 on usrtbl.userid=tbl2.userid order by tbl2.score
desc limit 1

To get details of user with max number of likes use following 要获得最多点赞次数的用户的详细信息,请使用以下代码

select usrtbl.username,usrtbl.userid,tbl3.numOfLikes from  usertable usrtbl inner join table3 tbl3 on usrtbl.userid=tbl3.userid order by tbl3.numOfLikes
desc limit 1

To get all in one query use following query 要获得全部查询,请使用以下查询

select usrtbl.username as 'user_with_max_score',usrtbl.userid as 'userid_of_user_with_max_score',
tbl2.score as 'max_score',usrtbl2.username as 'user_with_max_likes',usrtbl2.userid as 'userid_of_user_with_max_score' ,
tbl3.numOfLikes as 'max_likes' from  usertable usrtbl2 inner join table3 tbl3 inner join  usertable usrtbl inner join table2 tbl2 
on usrtbl.userid=tbl2.userid  and usrtbl2.userid=tbl3.userid order by tbl2.score desc,tbl3.numOfLikes desc
 limit 1

您可以选择表名 .name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM