简体   繁体   English

MySQL在查询的1个结果行中选择更多数据

[英]MySQL select more data in 1 result row of a query

I have a table - friends which has 2 columns, both are users table id 's. 我有一个表- friends有2列,都是usersid

I have a table - users which has id and username . 我有一个表- users拥有idusername

I need a query that will return username1 , username2 from the friends table, instead of id 's. 我需要一个查询,该查询将从friends表中返回username1username2 ,而不是id

I tried joining both tables, but it returns 2 result rows instead of one, which is not what I want. 我尝试加入两个表,但是它返回2个结果行而不是一个,这不是我想要的。

I tried looking into multi select queries, but I didn't find anything particularly useful, is it possible to do that? 我尝试研究多选查询,但没有发现任何特别有用的方法,有可能这样做吗?

Left join the users table twice, once for each user: 左联接users表两次,每个用户一次:

SELECT 
    u1.username username1, 
    u2.username username2
FROM friends f
LEFT JOIN users u1
    ON f.first_id = u1.id
LEFT JOIN users u2
    ON f.second_id = u2.id

Where first_id and second_id are the id columns in your friends table. 其中first_idsecond_id是您的friends表中的id列。

SQL Fiddle SQL小提琴

You can do it with 2 inner joins: 您可以使用2个内部联接来做到这一点:

SELECT
    User1.Name user1_name,
    User2.Name user2_name
FROM
    friends
    INNER JOIN users User1 ON friends.User1_ID = User1.ID
    INNER JOIN users User2 ON friends.User2_ID = User2.ID

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

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