create table a (name varchar(20) not null,sex varchar(10))
create table b (name varchar(20) not null,sex varchar(10))
2、插入值
insert into a values('john','male')insert into b values('john','male')
insert into a values('kate','female')insert into b values('kate','female')
3、查询方法1
mysql>select name,sex from a where name in (select name from b where name='john')
+------+------+
| name | sex |
+------+------+
| john | male |
+------+------+
1 row in set (0.00 sec)
4、查询方法2
mysql>select a.name,a.sex from a,b where a.name=b.name and b.name='john'
+------+------+
| name | sex |
+------+------+
| john | male |
+------+------+
1 row in set (0.00 sec)
使用联合查询,以下例子来说明联合查询(内联、左联、右联、全联)的好处:T1表结构(用户名,密码) userid(int) usernamevarchar(20) passwordvarchar(20) 1 jack jackpwd 2 owen owenpwd T2表结构(用户名,密码) userid(int) jifenvarchar(20) dengjivarchar(20)1 20 33 50 6 第一:内联(inner join)如果想把用户信息、积分、等级都列出来,那么一般会这样写:select * from T1, T3 where T1.userid = T3.userid(其实这样的结果等同于select * from T1 inner join T3 on T1.userid=T3.userid )。把两个表中都存在userid的行拼成一行(即内联),但后者的效率会比前者高很多,建议用后者(内联)的写法。SQL语句:select * from T1 inner join T2 on T1.userid = T2.userid运行结果 T1.userid username password T2.userid jifen dengji 1 jack jackpwd 1 20 3 第二:左联(left outer join)显示左表T1中的所有行,并把右表T2中符合条件加到左表T1中;右表T2中不符合条件,就不用加入结果表中,并且NULL表示。SQL语句:select * from T1 left outer join T2 on T1.userid = T2.userid运行结果 T1.userid username password T2.userid jifen dengji 1 jack jackpwd 1 20 3 2 owen owenpwd NULL NULL NULL 第三:右联(right outer join)。显示右表T2中的所有行,并把左表T1中符合条件加到右表T2中;左表T1中不符合条件,就不用加入结果表中,并且NULL表示。SQL语句:select * from T1 right outer join T2 on T1.userid = T2.userid运行结果 T1.userid username password T2.userid jifen dengji 1 jack jackpwd 1 20 3 NULL NULL NULL 3 50 6 第四:全联(full outer join)显示左表T1、右表T2两边中的所有行,即把左联结果表 + 右联结果表组合在一起,然后过滤掉重复的。SQL语句:select * from T1 full outer join T2 on T1.userid = T2.userid运行结果 T1.userid username password T2.userid jifen dengji 1 jack jackpwd 1 20 3 2 owen owenpwd NULL NULL NULL NULL NULL NULL 3 50 6第一种 exists与not existsselect * from table1 t1 where exists(select columnName from table2 t2 where t1.columnName2 = t2.columnName2)
第二种,in,not in的用法
select * from table1 where columnName in(select columnName from table2 where columnNane = 'condition')
第三种,any,all与比较运算的用法
-- 与任意一个比较返回真
select * from table1 where columnName >any(select columnName from table2 where columnNane = 'condition')
-- 与所有的值比较返回真
select * from table1 where columnName >all(select columnName from table2 where columnNane = 'condition')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)