Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

sql server - Select Name instead OF ID in table with ID-Ref Column SQL

Lets say we have 2 Tables:

 Table A        Table B
 - A_ID         - B_ID
 - A_Name       - A_ID

I need a select statement, that selects * from Table B showing the A_NAME instead of the A_ID.

By trying it I got the following select statement which ... doesn't work to well. It is giving me a lot of nulls, but no names.

SELECT B_ID, 
       (select A_NAME from TableA as A where A.A_ID = B.A_ID) as Name
FROM TableB as B

Thanks for all your Answers.

The final solution:

The shown query DOES work (even though it may be slow) and the solutions in the answers also do work.

The problem why it didn't give results for me was because of my data. On another database with the same schema all the commands work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should try LEFT JOIN

SELECT 
 B_ID, A_Name 
FROM 
 tableB B LEFT JOIN tableA A
   ON B.A_ID = A.A_ID

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...