如何选择要引用的列?

How can I choose which column do I refer to?

我有 2 个 table 有一些重复的列。我需要加入他们 而无需选择我想要的列 select:

CREATE TABLE IF NOT EXISTS animals (
  id int(6) unsigned NOT NULL,
  cond varchar(200) NOT NULL,
  animal varchar(200) NOT NULL,
  PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;

INSERT INTO animals (id, cond, animal) VALUES
  ('1', 'fat', 'cat'),
  ('2', 'slim', 'cat'),
  ('3', 'fat', 'dog'),
  ('4', 'slim', 'dog'),
  ('5', 'normal', 'dog');
  
CREATE TABLE IF NOT EXISTS names (
  id int(6) unsigned NOT NULL,
  name varchar(200) NOT NULL,
  animal varchar(200) NOT NULL,
  PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;

INSERT INTO names (id, name, animal) VALUES
  ('1', 'LuLu', 'cat'),
  ('2', 'DoDo', 'cat'),
  ('3', 'Jack', 'dog'),
  ('4', 'Shorty', 'dog'),
  ('5', 'Stinky', 'dog');

SELECT *
FROM animals AS a
JOIN names as n
ON a.id = n.id;

结果:

| id  | cond   | animal | id  | name   | animal |
| --- | ------ | ------ | --- | ------ | ------ |
| 1   | fat    | cat    | 1   | LuLu   | cat    |
| 2   | slim   | cat    | 2   | DoDo   | cat    |
| 3   | fat    | dog    | 3   | Jack   | dog    |
| 4   | slim   | dog    | 4   | Shorty | dog    |
| 5   | normal | dog    | 5   | Stinky | dog    |

但是当我尝试从结果 table 发出另一个请求时,例如:

SELECT name
FROM
(
SELECT *
FROM animals AS a
JOIN names as n
ON a.id = n.id
) as res_tbl
WHERE name = 'LuLu';

我得到:

Query Error: Error: ER_DUP_FIELDNAME: Duplicate column name 'id'

除了从第一个请求中删除重复的列之外,是否有任何方法可以避免它?

P.S。事实上,我使用的是 PostgreSQL,我将模式创建为 MySQL 因为我更习惯它

您在两个表中都有同名的列,这会导致歧义。

如果您只想要外部查询中的 name 列,那么 select 该列仅在子查询中:

select name
from (
    select n.name
    from animals a
    inner join names n using (id)
) t
where ...

如果您想要更多的列,那么您通常会为同音异义列添加别名以消除歧义 - 至于连接列(此处为 id),using() 语法就足够了。所以,例如:

select ...
from (
    select id, a.cond, a.animal as animal1, n.name, n.animal as animal2
    from animals a
    inner join names n using (id)
) t
where ...

您还可以 select 记录本身,而不是记录中的列,然后您可以使用通常的 record.column 语法在外部查询中访问它们;

SELECT a.cond animal_cond,
       n.name animal_name
FROM (
SELECT a, n
FROM animals AS a
JOIN names as n
ON a.id = n.id
) t