比如表1中有名为id name的两列列。。对应三组数据:
1 aaa
2 bbb
3 ccc;
表2 有名为 id2 name2 的列,有四组数值
4 ddd
5eee
6 fff
7 ggg
怎么用一条sql语句把aaa bbb ccc ddd eee fff ggg 这所有的数据都查找出来?
就是说两个不同的数据表,列的数量不同,但有一组相同类型的数据,现在把这两个数据表中这些数据都查询出来,这个该怎么实现?
ãã举ä¾è¯´æï¼ï¼ææ°æ®åºä¸æ3å¼ è¡¨åå«ä¸ºï¼userinfoï¼depï¼sexï¼
ããuserinfoï¼ç¨æ·ä¿¡æ¯è¡¨ï¼è¡¨ä¸æä¸ä¸ªå段åå«ä¸ºï¼user_diï¼ç¨æ·ç¼å·ï¼,user_nameï¼ç¨æ·å§åï¼,user_depï¼ç¨æ·é¨é¨ï¼ ãï¼å ³ç³»è¯´æï¼userinfo表ä¸çuser_depå段ådep表ä¸çdep_idå段为主å¤é®å ³ç³»ï¼userinfo表ä¸çuser_sexå段åsex表ä¸çsex_idå段为主å¤é®å ³ç³»ï¼
depï¼é¨é¨è¡¨ï¼è¡¨ä¸æ两个å段åå«ä¸ºï¼dep_idï¼é¨é¨ç¼å·ï¼,dep_nameï¼é¨é¨å称ï¼ãï¼ä¸»é®è¯´æï¼dep_id为主é®ï¼
sexï¼æ§å«è¡¨ï¼è¡¨ä¸æ两个å段åå«ä¸ºï¼sex_idï¼æ§å«ç¼å·ï¼ï¼sex_nameï¼æ§å«å称ï¼ãï¼ä¸»é®è¯´æï¼sex_id为主é®ï¼
ä¸ï¼ä¸¤å¼ è¡¨å ³é®æ¥è¯¢
1ãå¨userinfoï¼ç¨æ·ä¿¡æ¯è¡¨ï¼ä¸æ¾ç¤ºæ¯ä¸ä¸ªç¨æ·å±äºåªä¸ä¸ªé¨é¨ãsqlè¯å¥ä¸ºï¼
select userinfo.user_di,userinfo.user_name,dep_name from userinfo,dep where userinfo.user_dep=dep.dep_id2ãå¨userinfoï¼ç¨æ·ä¿¡æ¯è¡¨ï¼ä¸æ¾ç¤ºæ¯ä¸ä¸ªç¨æ·çæ§å«ãsqlè¯å¥ä¸ºï¼
select userinfo.user_di,userinfo.user_name,sex.sex_name from userinfo,sex where userinfo.user_sex=sex.sex_id
äºãå¤å¼ è¡¨å ³é®æ¥è¯¢
æåæ¥è¯¢åºæ¥çuserinfoï¼ç¨æ·ä¿¡æ¯è¡¨ï¼è¡¨ä¸é¨é¨åæ§å«é½æ¯ä»¥æ°åæ¾ç¤ºåºæ¥çï¼å¦æè¦æ³å¨ä¸å¼ 表ä¸å°é¨é¨åæ§å«é½ç¨æ±åæ¾ç¤ºåºæ¥ï¼éè¦å°ä¸å¼ 表åæ¶å ³èæ¥è¯¢æè½å®ç°ã
sqlè¯å¥ä¸ºï¼
select userinfo.user_di,userinfo.user_name,dep.dep_name,sex.sex_name from userinfo,dep,sex where userinfo.user_dep=dep.dep_id and userinfo.user_sex=sex.sex_idï¼å¤ä¸ªæ¡ä»¶ç¨andå ³èï¼
举例说明:某数据库中有3张表分别为:userinfo,dep,sex
userinfo(用户信息表)表中有三个字段分别为:user_di(用户编号),user_name(用户姓名),user_dep(用户部门) 。
dep(部门表)表中有两个字段分别为:dep_id(部门编号),dep_name(部门名称)。
sex(性别表)表中有两个字段分别为:sex_id(性别编号),sex_name(性别名称)。
一,两张表关键查询
1、在userinfo(用户信息表)中显示每一个用户属于哪一个部门。sql语句为:
select userinfo.user_di,userinfo.user_name,dep_name from userinfo,dep where userinfo.user_dep=dep.dep_id
2、在userinfo(用户信息表)中显示每一个用户的性别。sql语句为:
select userinfo.user_di,userinfo.user_name,sex.sex_name from userinfo,sex where userinfo.user_sex=sex.sex_id
二、多张表关键查询
最初查询出来的userinfo(用户信息表)表中部门和性别都是以数字显示出来的,如果要想在一张表中将部门和性别都用汉字显示出来,需要将三张表同时关联查询才能实现。
sql语句为:
select userinfo.user_di,userinfo.user_name,dep.dep_name,sex.sex_name from userinfo,dep,sex where userinfo.user_dep=dep.dep_id and userinfo.user_sex=sex.sex_id
脚本>>
create table table_1 (t_id number ,t_name varchar2(10));
insert into table_1 values (1,'aaa');
insert into table_1 values (2,'bbb');
insert into table_1 values (3,'ccc');
commit;
create table table_2 (t_id number ,t_name varchar2(10));
insert into table_2 values (4,'ddd');
insert into table_2 values (5,'eee');
insert into table_2 values (6,'fff');
insert into table_2 values (7,'ggg');
commit;
select * from table_1 union all select * from table_2;
结果>>