I'm trying to find a way to make my queries easier to read.

Say I have a table: with IDs, names, and partners. Partners is a list of ids.

 - 0, john, null
 - 1, mike, "0,2"
 - 2, sarah, "0,1"

Is there a way I can do a subquery to show names instead of the partner ids? select u.id, u.name, (select i.name from users i where i.id in u.parners) from users;

Something so I can get results like:

 - 0, john, null
 - 1, mike, "john,sarah"
 - 2, sarah, "john, mike"

I've tried something like what I've shown above, but I can't figure out anything special. Any help would be appreciated!

有帮助吗?

解决方案

Normalization is the best way for this. Otherwise, see FIND_IN_SET()

SELECT  a.ID,
        a.Name,
        GROUP_CONCAT(b.Name) Partners
FROM    tableName a
        LEFT JOIN tableName b
            ON FIND_IN_SET(b.id, a.partners)
GROUP   BY a.ID, a.Name

Suggested schema:

UserList

  • ID (PK)
  • Name
  • other columns

Partners

  • UserID (FK to UserList.ID)
  • PartnerID (FK to UserList.ID)

其他提示

It is better to follow Normalization rules as this is a One to Many relationship.

I have created two tables here

1.users

create table users(
id int not null auto_increment,
name varchar(40) not null,
primary key(id)
);

insert into users( name)  values ('John'),('Mike'),('Sarah');

+----+-------+
| id | name  |
+----+-------+
|  1 | John  |
|  2 | Mike  |
|  3 | Sarah |
+----+-------+

2.partners

create table users(
id int not null auto_increment,
name varchar(40) not null,
primary key(id)
);

insert into partners values (2,1),(2,3),(3,1),(3,2);

+---------+------------+
| user_id | partner_id |
+---------+------------+
|       2 |          1 |
|       3 |          1 |
|       3 |          2 |
|       2 |          3 |
+---------+------------+

You can use the following query to select Users and their partner

select u.name Users, group_concat(u1.name) Partners from users u 
left join partners p on u.id = p.user_id
left join users u1 on p.partner_id = u1.id
group by Users;

Output:

+-------+------------+
| Users | Partners   |
+-------+------------+
| John  | NULL       |
| Mike  | John,Sarah |
| Sarah | John,Mike  |
+-------+------------+
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top