如何将 table 与每个 id 有两条记录的自身连接起来?
How to join a table with itself with two records per id?
所以,我有一个具有以下结构的 table:
编号
A 列
B 列
1
是
1
没有
我想把一行合并成一行,所以结果是这样的:
编号
A 列
B 列
1
是
没有
我相信这里的自我加入会像这样工作:
SELECT t1.columnA , t2.columnB
FROM table1 t1, table1 t2
where t1.id = t2.id
但是有没有办法在不指定列的情况下做到这一点?我有一个包含 100 列的 table,我正在尝试查看是否可以在不列出所有列的情况下完成此操作。
is there a way to do this without specifying the columns?
您可以使用 using
来回答您的问题。
SELECT t1.columnA , t2.columnB
FROM table1 t1 JOIN
table1 t2
USING (id);
要获取您想要的数据,请使用聚合:
SELECT id, MAX(t1.columnA), MAX(t2.columnB)
FROM table1 t1
GROUP BY id;
使用您的 JOIN 仅更改 *
的列
SELECT t1.*, t2.*
FROM table1 t1, table1 t2
where t1.id = t2.id
使用以下查询获取带有聚合的列名(使用信息模式创建的查询以获取列名)。使用结果和 运行 写一个 select 查询。
select
case when column_name='Id' then column_name
else concat(',Max(', column_name,')') end as Name
from information_schema.columns
where table_name = 'Table1';
您将得到如下所示的输出,其中 A 和 B 是列名。
Id
,Max(A)
,Max(B)
添加将结果转换为查询
Select
Id
,Max(A)
,Max(B)
from Table1 Group by Id
所以,我有一个具有以下结构的 table:
编号 | A 列 | B 列 |
---|---|---|
1 | 是 | |
1 | 没有 |
我想把一行合并成一行,所以结果是这样的:
编号 | A 列 | B 列 |
---|---|---|
1 | 是 | 没有 |
我相信这里的自我加入会像这样工作:
SELECT t1.columnA , t2.columnB
FROM table1 t1, table1 t2
where t1.id = t2.id
但是有没有办法在不指定列的情况下做到这一点?我有一个包含 100 列的 table,我正在尝试查看是否可以在不列出所有列的情况下完成此操作。
is there a way to do this without specifying the columns?
您可以使用 using
来回答您的问题。
SELECT t1.columnA , t2.columnB
FROM table1 t1 JOIN
table1 t2
USING (id);
要获取您想要的数据,请使用聚合:
SELECT id, MAX(t1.columnA), MAX(t2.columnB)
FROM table1 t1
GROUP BY id;
使用您的 JOIN 仅更改 *
的列SELECT t1.*, t2.*
FROM table1 t1, table1 t2
where t1.id = t2.id
使用以下查询获取带有聚合的列名(使用信息模式创建的查询以获取列名)。使用结果和 运行 写一个 select 查询。
select
case when column_name='Id' then column_name
else concat(',Max(', column_name,')') end as Name
from information_schema.columns
where table_name = 'Table1';
您将得到如下所示的输出,其中 A 和 B 是列名。
Id
,Max(A)
,Max(B)
添加将结果转换为查询
Select
Id
,Max(A)
,Max(B)
from Table1 Group by Id