请教一个SQL语句,希望大家帮忙!

yshuui 2008-05-16 12:34:54
有这样一个数据库表格

字段1 字段2 字段3 字段4 字段5 字段6
1 2 a a1 b b1
2 3 c c1 a a2

想得到‘字段3’或者‘字段5’=a的记录
字段4和字段3,字段6和字段5是相关的,一起查出来。

要查询的结果为
字段1 字段2 字段3 字段4
1 2 a a1
2 3 a a2

请教用sql怎么做查询?
...全文
110 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
zanyzyg 2008-05-16
  • 打赏
  • 举报
回复
不好意思,少了where部分

借用一下

create table tb(col1 int,col2 int,col3 varchar(10),col4 varchar(10),col5 varchar(10),col6 varchar(10))
insert into tb select 1,2,'a','a1','b','b1' union all select 2,3,'c','c1','a','a2'

select col1,col2,case when col3='a' then col3 else col5 end as col3,case when col3='a' then col4 else col6 end as col4 from tb where col3='1' or col5='a'

drop table tb
zanyzyg 2008-05-16
  • 打赏
  • 举报
回复

借用一下

create table tb(col1 int,col2 int,col3 varchar(10),col4 varchar(10),col5 varchar(10),col6 varchar(10))
insert into tb select 1,2,'a','a1','b','b1' union all select 2,3,'c','c1','a','a2'

select col1,col2,case when col3='a' then col3 else col5 end as col3,case when col3='a' then col4 else col6 end as col4 from tb

drop table tb
lff642 2008-05-16
  • 打赏
  • 举报
回复


---result
/*
col1 col2 col3 col4
1 2 a a1
2 3 a a2

*/
lff642 2008-05-16
  • 打赏
  • 举报
回复


--try
create table tb(col1 int,col2 int,col3 varchar(10),col4 varchar(10),col5 varchar(10),col6 varchar(10))
insert into tb select 1,2,'a','a1','b','b1' union all select 2,3,'c','c1','a','a2'

select col1,col2,col3,col4 from tb where col3 = 'a'
union all
select col1,col2,col5,col6 from tb where col5='a'

drop table tb


pt1314917 2008-05-16
  • 打赏
  • 举报
回复
字段1 字段2 字段3 字段4
1 2 a a1
2 3 a a2

红色部分的结果是怎么来的?
jinjazz 2008-05-16
  • 打赏
  • 举报
回复
select * from tb where 字段3 ='a' or 字段5='a'
yshuui 2008-05-16
  • 打赏
  • 举报
回复
select 字段1 字段2 字段3 字段4 from table where 字段3='a'
union
select 字段1 字段2 字段5 字段6 from table where 字段5='a'
yshuui 2008-05-16
  • 打赏
  • 举报
回复
谢谢大家,已经解决。
qys2000 2008-05-16
  • 打赏
  • 举报
回复
select * from tb where 字段3 ='a' or 字段5='a'
swot2008 2008-05-16
  • 打赏
  • 举报
回复

select 字段1,字段2,字段3,字段4
from tab
where 字段3 ='a' or 字段5='a'
swot2008 2008-05-16
  • 打赏
  • 举报
回复
[code=SQL]select 字段1,字段2,字段3,字段4 
from tab
where 字段3 ='a' or 字段5='a'
[/code]
zhou968 2008-05-16
  • 打赏
  • 举报
回复

create table tb(col1 int,col2 int,col3 varchar(10),col4 varchar(10),col5 varchar(10),col6 varchar(10))
insert into tb select 1,2,'a','a1','b','b1' union all select 2,3,'c','c1','a','a2'

select col1,col2,col3,col4 from tb where col3 = 'a'
union all
select col1,col2,col5,col6 from tb where col5='a'

ojuju10 2008-05-16
  • 打赏
  • 举报
回复


create table aa(c1 int,c2 int,c3 varchar(10),c4 varchar(10),c5 varchar(10),c6 varchar(10))
insert into aa select 1, 2, 'a', 'a1', 'b', 'b1'
insert into aa select 2, 3, 'c', 'c1', 'a', 'a2'

select c1,c2,c3,c4 from aa a
where c3='a'
union all
select c1,c2,c5,c6 from aa a
where c5='a'

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧