很多时候需要查询两张表及以上的表来获取需要的信息
一张表的时候查询语句:
select 列1,列2 from 表 where 查询条件
例如:一张表
username | age | sex |
张三 | 24 | 男 |
李四 | 23 | 女 |
王麻子 | 22 | 男 |
查询一张表中的数据
select username, age from 信息表 where username="王麻子"
查询出来的结果
username | age |
王麻子 | 22 |
两个表的时候查询语句
① select 表1.列1, 表1.列2,表2.列1 from 表1,表2 where 表1.列x=表2.列x
user | age | user_id |
张三 | 20 | 111 |
李四 | 18 | 123 |
赵五 | 32 | 345 |
还有另一张表
user_id | wuqi |
123 | 铁锤 |
345 | 大炮 |
用这两个表查用户名和所使用的武器
① select LOL.user ,LOLp.wuqi from LOL,LOLp where LOL.user_id=LOLp.user_id
这样的结果就是
user | wuqi |
李四 | 铁锤 |
赵五 | 大炮 |
② select LOL.user ,LOLp.wuqi from LOL left join LOLp on LOL.user_id=LOLp.user_id where 筛选条件(在不需要筛选条件的时候没有where语句)
其他的查找方式:
SELECT
distinct
a.userId,a.tijianhao,a.SURVEYID,
a.tbrq as rq,
convert(varchar(10),a.tbrq,120) as tbrq,
a.tijianhao as TJH,
isViewed,
b.jieguo as name, //这里可以修改正(select jieguo from where tijianhao=a.tijianhao and xmcode="name")name,
b.flag as TYPE,
a.has_survey
FROM SHANGWURECORD a
left join ShangWuJieGuo b on a.tijianhao=b.tijianhao and b.xmcode='name'
where a.SURVEYID !='' and a.userid='1234567898763' and belong_id='1234567898763' order by a.tbrq desc
//比如 带有别名的
SELECT
distinct
a.userId,a.tijianhao,a.SURVEYID,
a.tbrq as rq,
convert(varchar(10),a.tbrq,120) as tbrq,
a.tijianhao as TJH,
isViewed,
(select jieguo from where tijianhao=a.tijianhao and xmcode="name")name,//刚才修改的地方
b.flag as TYPE,
a.has_survey
FROM SHANGWURECORD a
left join ShangWuJieGuo b on a.tijianhao=b.tijianhao //还有这里的变化
where a.SURVEYID !='' and a.userid='440Y98F1DQX8' and belong_id='440Y98F1DQX8' order by a.tbrq desc
第①中一样的 很重复的表名还是用上面整个别名比较好
select distinct SHANGWURECORD.userId,
SHANGWURECORD.tijianhao,
SHANGWURECORD.SURVEYID,
SHANGWURECORD.tbrq as rq,
convert(varchar(10),SHANGWURECORD.tbrq,120) as tbrq,
isViewed,
ShangWuJieGuo.jieguo as name,
ShangWuJieGuo.flag as TYPE,
SHANGWURECORD.has_survey
from SHANGWURECORD,ShangWuJieGuo
where SHANGWURECORD.tijianhao=ShangWuJieGuo.tijianhao
and SHANGWURECORD.userid='440Y98F1DQX8' and belong_id='440Y98F1DQX8' and ShangWuJieGuo.xmcode='name'