MySQL - 这在一个查询中是否可行?

k00*_*00k 0 mysql sql

我目前正在运行以下查询:

SELECT*来自人WHERE id = 4;

在下表中:

id       name          state   age
-----------------------------------
1       tony jones     CA      22
2       Sue Smith      FL      50
3       Alex Guam      AL      44
4       tony jones     SC      32
5       tony jones     OH      12
6       alex guam      RI      33
7       tony Jones     CO      17
Run Code Online (Sandbox Code Playgroud)

我还要返回一个以该名字命名的其他州的名单.

所以在我的查询示例中,我有"tony jones"的id 4 - 我还应该收到CA,OH,CO的"other_states"列表.

是否可以在一个查询中或者我需要在基于"名称"的事实之后进行单独选择?

Jam*_*lis 5

这将为您提供您想要的东西:

select t.id,
       t.name,
       t.age,
       t.group_concat(distinct t.state order by t.state separator ', ') as other_states
from   the_table t
    inner join the_table u on t.name = u.name 
where  u.id = 4
group by t.id, t.name, t.age
Run Code Online (Sandbox Code Playgroud)