简体   繁体   English

如何创建一个新列来保存具有相同值的所有行的所有主键值?

[英]How do I create a new column that holds all the primary key values of all rows that have the same value?

I read through multiple Questions here, but did not find the answer suiting my problem.我在这里阅读了多个问题,但没有找到适合我的问题的答案。

My table holds the following columns:我的表包含以下列:

id |  name    |  fav_team
 1    John       Seahawks
 2    Patrick    Bengals
 3    Tom        Seahawks
 4    Kate       Seahawks

So I already figured out how to ask for all ids whose fav_team is 'Seahawks' but how do I manage to create a new column that for id 1 holds all the ids of that rows that have 'Seahawks' as fav_team as well, so that my output will look like this:所以我已经想出了如何询问所有 fav_team 为“Seahawks”的 id,但是我如何设法创建一个新列,其中 id 1 包含所有具有“Seahawks”作为 fav_team 的行的 id,这样我的 output 将如下所示:

id    |   same_team
 1        3, 4
 3        1, 4
 4        1, 3

use group_concat()使用 group_concat()

    select group_concat(id) from table t1
     where exists ( select 1 from table t2 where t1.fav_team=t2.fav_team
                  ) and 

You can us a correlated subquery:您可以使用相关子查询:

select t.*,
       (select group_concat(id order by id)
        from t t2
        where t2.fav_team = t.fav_team and t2.id <> t.id
       ) as others_with_same_favorite
from t;

You can also do this with window functions, but it requires diving into JSON and doing a lot of string manipulation:您也可以使用 window 函数执行此操作,但需要深入了解 JSON 并进行大量字符串操作:

select id,
       trim(',' from
            replace(regexp_replace(json_unquote(json_arrayagg(id) over (partition by fav_team)), '\\[|\\]|, ', ','),
                    concat(',', id, ','), ','
                   )
           )
from t
order by id;

Here is a db<>fiddle for this version. 是此版本的 db<>fiddle。

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

相关问题 如何选择不同的行,其中一列可能具有许多相同的值,但所有第二列均具有相同的值? - How do I select distinct rows where a column may have a number of the same values but all their 2nd columns have the same value? 如何检查所有行是否具有相同的列值? - How can I check if all rows have the same column value? 如何选择具有相同值的所有列值的行? - How can I select rows with all Column value, which have the same values? 通过查询同一列获取具有所有输入值的所有行 - Getting all rows that have all of the entered values by querying the same column 当行的值相同时,如何更改主键? - How do you change the primary key, when rows have the same value? 如何为列的相同值选择所有行? - How to select all rows for same value of column? 如何更新表以添加主键并使用递增的ID更新所有现有行? - How do I update a table to add a primary key and update all of the existing rows with incremented IDs? SQL-如何选择列中具有value1但同一列中没有value2的所有行? - SQL - how to select all rows which have value1 in column but not value2 in same column? 如何查找具有所有其他列值的所有行 - How to find all rows that have all another column values 获取所有行具有相同列值的mysql数据 - Getting mysql data where all rows have same column value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM