试了好几次,报错误的一条语句..关于if()..关联两个表..在线等结贴 (刚才忘给分了,现在补上)
表A 员工基本信息
Bid name age sex
1 sss 18 Y
2 FFF 19 N
3 EEE 32 Y
4 EW 23 Y
5 FEFE 32 N
表B 某部门成员表
cid Bid
1 4
2 5
表B.Bid 外键引用表A.Bid
期待结果 : (对于A表的记录,如果在B表有相关记录,则isInB为Y 否则为N)
Bid name age sex IsInB
1 sss 18 Y N
2 FFF 19 N N
3 EEE 32 Y N
4 EW 23 Y Y
5 FEFE 32 N Y
试验语句: select a.*,
(if(exists(select * from b where b.bid=a.bid)) select 'Y ' else select 'N ') isInB
from a
报告错误,if附近有语法错误,
求能得到我期望结果的SQL语句...在线等 有结果就结贴
[解决办法]
create table a
(Bid int, name varchar(10), age int, sex varchar(10) )
insert into a
select 1 , 'sss', 18 , 'Y' union all
select 2 , 'FFF', 19 , 'N' union all
select 3 , 'EEE', 32 , 'Y' union all
select 4 , 'EW' , 23 , 'Y' union all
select 5 , 'FEFE', 32 , 'N'
create table b
(cid int, Bid int )
insert into b
select 1, 4 union all
select 2, 5
select t1.*,IsInB =case when t1. Bid=t2. Bid then 'Y ' else 'N ' end
from A t1 left join B t2
on t1. Bid=t2. Bid
Bid name age sex IsInB
----------- ---------- ----------- ---------- -----
1 sss 18 Y N
2 FFF 19 N N
3 EEE 32 Y N
4 EW 23 Y Y
5 FEFE 32 N Y
(所影响的行数为 5 行)
[解决办法]
--这个更简单点.create table A(Bid int,name varchar(10),age int,sex varchar(2))insert into A values(1, 'sss' , 18, 'Y') insert into A values(2, 'FFF' , 19, 'N') insert into A values(3, 'EEE' , 32, 'Y') insert into A values(4, 'EW' , 23, 'Y') insert into A values(5, 'FEFE', 32, 'N')create table B(cid int,Bid int)insert into B values(1, 4) insert into B values(2, 5)goselect A.* , IsInB = case when a.bid in (select bid from B) then 'Y' else 'N' endfrom A drop table A,B/*Bid name age sex IsInB ----------- ---------- ----------- ---- ----- 1 sss 18 Y N2 FFF 19 N N3 EEE 32 Y N4 EW 23 Y Y5 FEFE 32 N Y(所影响的行数为 5 行)*/