我正在寻找输出:
| BOOK | ANALYST | SUPERVISOR |
|-------|----------------|--------------------|
| BookA | (null) | Dani Sant |
| BookB | (null) | North Andre Miles |
| BookC | Andrea Plus | Andrea Plus |
| BookD | Jeff Dron Math | Jeff Dron Math |
| BookE | Theo Phillip | Julian Rhode |
我得到的是:
| BOOK | ANALYST | SUPERVISOR |
|-------|----------------|--------------|
| BookA | (null) | dani.sant |
| BookB | (null) | north.miles |
| BookC | Andrea Plus | andrea.plus |
| BookD | Jeff Dron Math | jeff.math |
| BookE | Theo Phillip | julian.rhode |
我可以使用一列进行连接,但是当我尝试两者时,结果不会显示它应该如此。感谢您提供任何相关信息。
MS SQL Server 2008架构设置:
CREATE TABLE books
(
book varchar(10),
analyst varchar(100),
supervisor varchar(100)
);
INSERT INTO books (book, analyst, supervisor)
VALUES
('BookA', NULL, 'dani.sant'),
('BookB', NULL, 'north.miles'),
('BookC', 'andrea.plus', 'andrea.plus'),
('BookD', 'jeff.math', 'jeff.math'),
('BookE', 'theo.phil', 'julian.rhode');
CREATE TABLE names
(
username varchar(100),
fullname varchar(500)
);
INSERT INTO names (username, fullname)
VALUES
('dani.sant', 'Dani Sant'),
('north.miles', 'North Andre Miles'),
('andrea.plus', 'Andrea Plus'),
('jeff.math', 'Jeff Dron Math'),
('theo.phil', 'Theo Phillip'),
('julian.rhode', 'Julian Rhode');
查询1 :
SELECT
books.book AS Book,
names.fullname AS Analyst,
books.supervisor AS Supervisor
FROM
books left join names on books.analyst = names.username
Results :
| BOOK | ANALYST | SUPERVISOR |
|-------|----------------|--------------|
| BookA | (null) | dani.sant |
| BookB | (null) | north.miles |
| BookC | Andrea Plus | andrea.plus |
| BookD | Jeff Dron Math | jeff.math |
| BookE | Theo Phillip | julian.rhode |
答案 0 :(得分:2)
您需要第二个join
到names
表格才能获得主管的全名:
SELECT b.book AS Book, bn.fullname AS Analyst,
sn.fullname AS Supervisor
FROM books b left join
names bn
on b.analyst = bn.username left join
names sn
on b.supervisor = sn.username;
答案 1 :(得分:1)
下面将提供您想要的输出。
SELECT
b.book AS Book,
n.fullname AS Analyst,
(SELECT fullname FROM names where username=b.Supervisor) AS Supervisor
FROM
books b left join names n on b.analyst = n.username