高分求救,一个高难度的SQL语句??

田九 2006-11-19 05:19:42
一个高难度的SQL语句,不知道能不能实现。
如果表A有符合条件的,就取A的记录,如果没有就取表B的记录。
表A和表B结构是一样的
...全文
459 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
xueru9999 2006-11-29
  • 打赏
  • 举报
回复
我同意love_2008(love2008) 的写法
小李木耳 2006-11-29
  • 打赏
  • 举报
回复
select * from a1 where 条件
union
select * from a2 where 条件 and (select count(*) from a1 where 条件)=0
wangzk0206 2006-11-28
  • 打赏
  • 举报
回复
select * from a where 条件
union
select * from b where 条件 and not exists (select 1 from a where 条件)
Eric_1999 2006-11-28
  • 打赏
  • 举报
回复
select * from a where exist (select 1 from a where 你的条件)
union
select * from b where exist (select 1 from b where 你的条件)
and not exist (select 1 from a where 你的条件)
tongyu10068 2006-11-20
  • 打赏
  • 举报
回复
declare
v_temp number(10);
v_temp2 varchar(30);
begin
v_temp2 :=&输入条件;
select count(*) into v_temp from a where 列名 =v_temp2;
if (v_temp)!=0 then
select * from a where 列名 =v_temp2;
else
select * from b where 列名 =v_temp2;
end if;
end;
kingkingkingking 2006-11-20
  • 打赏
  • 举报
回复
如果结构相同,数据量不是很大
用以下语句
select * from a1 where 条件
union
select * from a2 where 条件
两个语句的条件相同即可
hevin 2006-11-19
  • 打赏
  • 举报
回复
写了一个例子,你可以参考一下:

SQL> select * from a;

C1 C2
------- --------------------
100 Steven
101 Neena
102 Lex
103 Alexander
104 Bruce
105 David

6 rows selected

SQL> select * from b;

C1 C2
------- --------------------
103 Alexander
104 Bruce
105 David
106 Valli
107 Diana
108 Nancy
109 Daniel

7 rows selected

SQL>
SQL> SELECT *
2 FROM a
3 WHERE c1 > 101
4 UNION
5 SELECT *
6 FROM b
7 WHERE c1 > 101 AND NOT EXISTS (SELECT 1
8 FROM a
9 WHERE a.c1 > 101 AND rownum <=1);

C1 C2
------- --------------------
102 Lex
103 Alexander
104 Bruce
105 David

SQL>
SQL> SELECT *
2 FROM a
3 WHERE c1 > 106
4 UNION
5 SELECT *
6 FROM b
7 WHERE c1 > 106 AND NOT EXISTS (SELECT 1
8 FROM a
9 WHERE a.c1 > 106 AND rownum <=1);

C1 C2
------- --------------------
107 Diana
108 Nancy
109 Daniel

SQL>
SQL> SELECT *
2 FROM a
3 WHERE c1 = 101
4 UNION
5 SELECT *
6 FROM b
7 WHERE c1 =101 AND NOT EXISTS (SELECT 1
8 FROM a
9 WHERE a.c1 = 101 AND rownum <=1);

C1 C2
------- --------------------
101 Neena

SQL>
SQL> SELECT *
2 FROM a
3 WHERE c1 = 104
4 UNION
5 SELECT *
6 FROM b
7 WHERE c1 =104 AND NOT EXISTS (SELECT 1
8 FROM a
9 WHERE a.c1 = 104 AND rownum <=1);

C1 C2
------- --------------------
104 Bruce

SQL>
SQL> SELECT *
2 FROM a
3 WHERE c1 = 108
4 UNION
5 SELECT *
6 FROM b
7 WHERE c1 =108 AND NOT EXISTS (SELECT 1
8 FROM a
9 WHERE a.c1 = 108 AND rownum <=1);

C1 C2
------- --------------------
108 Nancy

SQL>
田九 2006-11-19
  • 打赏
  • 举报
回复
因为有可能,两个表都满足的情况呀。
田九 2006-11-19
  • 打赏
  • 举报
回复
这样写不行,如果该条件,都满足呢,不就都取出来了。
火龙岛主 2006-11-19
  • 打赏
  • 举报
回复
select * from a where exist (select 1 from a where 你的条件)
union
select * from b where exist (select 1 from b where 你的条件)

17,382

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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