加入三个表并获取ID值 [英] Joining three tables and getting ID value

查看:89
本文介绍了加入三个表并获取ID值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

我有三张桌子,如苹果,球和猫



apple只包含ID列(两者的ID)球和猫表)



球包含ID和球名称



cat包含ID和Cat名称。



解决方案我需要:

如何为这三个表添加连接以获取我传递的单个ID的名称?



我的查询:



For eg:
I am having three tables as apple, ball and cat

apple contains only ID column(ID's of both ball and cat tables)

ball contains ID and Ball Names

cat contains ID and Cat Names.

Solution I Need:
how do I put join for these three tables to get a name of a single ID which I am passing?

My Query:

select b.ball_name, c.cat_name from tbl_ball b join tbl_apple a join tbl_cat c
on ((b.ballId = a.Id) or (c.catId = a.Id)) where a.Id = 1100

推荐答案

如果您的表格结构如下:

If your table structure is like this:
--Apple Table
ID      cat_id      ball_id
---------------------------
1100        1         1

--Ball Table
ball_id         ball_name
---------------------------
1                  Ball 1

--Cat Table
cat_id          cat_name
---------------------------
1                  Cat 1



那么你的查询应该是这样的:


Then your query should be like:

SELECT B.ball_name,C.cat_name FROM apple A
INNER JOIN ball B ON A.ball_id = B.ball_id
INNER JOIN cat C ON A.cat_id = C.cat_id
WHERE A.ID = 1100 -- ID should be identity column of apple table



请参考:

MSDN:加入基础知识 [ ^ ]

MSDN:加入提示(Transact-SQL) [ ^ ]





- Amit


尝试

Try
select b.ball_name, c.cat_name 
from tbl_ball b join tbl_apple a on b.ballId = a.Id
join tbl_cat c on c.catId = a.Id
where a.Id = 1100





代码块已修复[/ edit]



[edit]Code block fixed[/edit]


SELECT b.ball_name,c.cat_name from tbl_apple a JOIN  tbl_ball b on a.id=b.id 
JOIN tbl_cat c on c.catid=a.id WHERE a.id=1100





试试这个,看看



Try this and see


这篇关于加入三个表并获取ID值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆