日期:2014-05-17  浏览次数:20472 次

求问如何连接两个表格
本帖最后由 zsdc0306 于 2013-08-19 15:20:51 编辑
比如说我现在查询出两个表,
|id  | name |
|001 | xxx  |
第二个
| dept | age |
| xxx  | 33  |
然后想变成
|id   | name | dept | age |
|001 | xxx  | xxx  | 33  |

sql语句怎么写啊?用union出来是一列的

------解决方案--------------------
select a.id,a.name,b.dept,b.age from 第一个表 a,第二个表 b where a.关键字=b.关键字
------解决方案--------------------
没有相关联的列吗?有的话直接JOIN一下就行了 没有的话就构造一个ID列 再JOIN
------解决方案--------------------
SELECT a.id,a.NAME,b.dept,b.age
FROM tabelA a
INNER JOIN tableB b
ON a.NAME = b.dept

------解决方案--------------------

create table testA(id nvarchar(10),name nvarchar(10))
insert into testA values('001','xxx')
create table testB(dept nvarchar(10),age int)
insert into testB values('xxx',33)

select *
from testA a 
INNER JOIN testB b
on a.name=b.dept

/*
id name dept age
001 xxx xxx 33
*/

------解决方案--------------------
SELECT MAX(id)id,MAX(name) NAME,MAX(dept)dept,MAX(age)age
FROM (
SELECT id,NAME,NULL dept,NULL age
FROM  tb1
UNION ALL 
SELECT NULL,NULL,dept,age
FROM tb2)a