日期:2014-05-17 浏览次数:20612 次
table_A
ID NAME
1 joe
2 tom
3 jack
table_B --关联表
ID stu_id pro_id
1 1 3
--现在想一行显示 joe jack
----------------------------
-- Author :DBA_Huangzj
-- Date :2013-01-08 16:26:45
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[table_A]
if object_id('[table_A]') is not null drop table [table_A]
go
create table [table_A]([ID] int,[NAME] varchar(4))
insert [table_A]
select 1,'joe' union all
select 2,'tom' union all
select 3,'jack'
--------------开始查询--------------------------
--select * from [table_A]
if object_id('[table_B]') is not null drop table [table_B]
go
create table [table_B]([ID] int,[stu_id] int,[pro_id] int)
insert [table_B]
select 1,1,3
--------------开始查询--------------------------
select b.*,A.NAME,c.name from [table_B] b INNER JOIN [table_A] a ON a.id=b.stu_id
INNER JOIN [table_A] c ON b.pro_id=c.id
/*
ID stu_id pro_id NAME name
----------- ----------- ----------- ---- ----
1 1 3 joe jack
(1 行受影响)
*/