指向同一个表的多个外键 - 歧义问题

时间:2012-08-14 00:34:57

标签: mysql sql foreign-key-relationship

我有一个MySQL数据库,其中包含一个包含两个外键的文章表:

  • fk_id_user_created
  • fk_id_user_edited

users表看起来像这样

  • pk_id_user
  • 用户名

如何连接这些表,以便返回创建和编辑文章的用户的用户名?显然存在歧义问题......

编辑:这显然不起作用:

SELECT
    articles.title,
    articles.article,
    users.username as created_by,
    users_username as edited_by
FROM
    articles
LEFT JOIN
    users
ON
    articles.fk_id_user_created = users.pk_id_username
LEFT JOIN
    users
ON
    articles.fk_id_user_edited = users.pk_id_username

2 个答案:

答案 0 :(得分:4)

使用users加入articles两次,提供别名来区分实例:

select  
  articles.whatever,
  created.username as created_username,
  edited.username as edited_username
from 
  articles
  inner join users as created on articles.fk_id_user_created = created.pk_id_user
  inner join users as edited  on articles.fk_id_user_edited  = edited.pk_id_user
;

答案 1 :(得分:0)

如果我理解正确的话,你的意思是这样吗?

CREATE TABLE USER (
user_id INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255)
);

INSERT INTO USER (username) VALUES
('A'), ('B');

CREATE TABLE article (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
user_id_created INTEGER,
user_id_edited INTEGER
);

INSERT INTO article (user_id_created, user_id_edited)
VALUES (1, 1), (2,1);

SELECT username 
FROM USER 
WHERE user_id IN (SELECT user_id_created FROM article WHERE user_id_created=user_id_edited);

DROP TABLE USER;
DROP TABLE article;

我没有使用连接,我只是假设user_id_created和user_id_edited将是相同的。