[英]MySql - Select user name from two different tables in one query
I have 3 tables 我有3张桌子
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 我在查询中使用以下三个表
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.