我有两个表,它们具有相同的 ID 名称(我无法更改表的设计方式),并且我正在尝试查询 table2 的 ID,当它们连接时我该怎么做?
create table table1(
id integer, -- PG: serial
description MediumString not null,
primary key (id)
);
create table table2 (
id integer, -- PG: serial
tid references table1(id),
primary key (id)
);
所以基本上当它们连接时,如果我执行以下查询,两列将具有相同的名称"id"
select * from table1
join table2 on table1.id = table2.tid;
如果需要两个"id",则别名列
SELECT table1.id AS id1, table2.id AS id2
FROM table1...
如果你想查询两个表上的所有 *,但仍然能够引用一个特定的 id,你也可以这样做,你最终会得到重复的 id 列,你可能不会使用,但在某些情况下,如果你真的需要所有数据,这是值得的。
select table1.*, table2.*, table1.id as 'table1.id', table2.id as 'table2.id'
from ...
不能使用 select *
来选择它。试试这个:
select table1.id, table1.description, table2.id, table2.tid
from table1
inner join table2
on table1.id = table2.tid