简体   繁体   中英

How can I get a column from another table in SQL Server?

I have two tables, Clients and Documents.

Client's table is defined like:

ID   | NAME    | ADDRESS | TELEPHONE 
112  | EXAMPLE | ABC#123 | 85548484
115  | WOAH!   | ABC#123 | 85548484

and the Document's table is like:

ID|Number|ClientID|Total
1 | 363  |  112   | 25000
2 | 364  |  112   | 24000
3 | 365  |  115   | 21000

How can I get results like that without using an INNER JOIN?:

ID|Number|ClientID|Total| NAME    | ADDRESS | TELEPHONE 
1 | 363  |  112   |25000| EXAMPLE | ABC#123 | 85548484
2 | 364  |  112   |24000| EXAMPLE | ABC#123 | 85548484
3 | 365  |  115   |21000| WOAH!   | ABC#123 | 85548484

I tried

Select Documents.*, 
       (Select *from Clients where DOcuments.ClientID = Clients.ID ) 
FROM Documents

but I got wrong results..

Thank you!

You can use apply :

select d.*, c.name, c.address, c.telephone
from documents d cross apply
     (select c.*
      from clients c
      where d.clientid = c.id
     ) c;

You could also use left join :

select d.*, c.name, c.address, c.telephone
from documents d left join
     clients c
     on d.clientid = c.id;

Or similar constructs using full join or right join or outer apply . The restriction on inner join is quite curious.

EDIT:

If you want to keep all clients, even those with no documents:

select d.*, c.name, c.address, c.telephone
from clients c left join
     documents d
     on d.clientid = c.id;

Try:

select d. , c. from documents d left join clients c on c.clientId = d.clientId -- add where clause and order by clause of your choosing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM