1

假设我有三个表:

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;

我可以通过以下查询成功提取用户信息及其对应的location信息:document

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

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

有没有一种查询表的方法,以便maintainer返回实际user数据而不是返回实际数据id

4

1 回答 1

2
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
于 2013-08-09T19:20:41.157 回答