【问题标题】:Joining tables back to themselves in MySql在 MySql 中将表连接回自身
【发布时间】:2013-08-10 03:20:41
【问题描述】:

假设我有三个表:

user表:

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `loc` int(11) DEFAULT NULL,
  `doc` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

location表:

CREATE TABLE `location` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

document 表:

CREATE TABLE `document` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `maintainer` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

我可以成功拉取用户信息,它对应locationdocument信息,查询如下:

SELECT * from `user` LEFT JOIN `location` on user.loc = location.id LEFT JOIN `document` on user.doc = document.id;

location 信息很容易被引用,因为它的信息不引用任何其他表中的任何其他行。但是,document 表包含一个maintainer 字段,该字段直接对应于user 表中的另一个user。这个字段封装了user的信息,并没有给我实际的user数据。

有没有办法查询表,以使maintainer 的数据返回实际的user 数据而不是id

【问题讨论】:

  • 自联接背后的一般思想是每次引用表时使用不同的别名。
  • @DanBracuk 需要详细说明吗?我不是特别精通SQL...

标签: mysql sql data-modeling


【解决方案1】:
select
    u.name as user_name,
    m.name as maintainer_name,
    l.name as location_name
from user as u
    left outer join document as d on d.id = u.doc
    left outer join user as m on m.id = d.maintainer
    left outer join location as l on l.id = u.loc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 2020-11-04
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    相关资源
    最近更新 更多