oracle 我有一个表'A',其中有119940377条记录,'A'表正在根据优先级从4个不同的表中获取值,

11dmarpk  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(122)

如果下面是四个表的记录,
| 第一桌|第二桌|第三桌|第四桌|
| --|--|--|--|
| 1 | 1 |第二,| 3 |
| 2 |第二,|第六章| 4 |
| 3. |5.第五章|第七章| 10 |
然后A表有来自第一个表的1,2,3,来自第二个表的5,来自第三个表的6,7和来自第四个表的4和10。

with a as (
select distinct a.id
from  a inner join 
first table b
on a.id=b.id),
b as(
select distinct a.id
from a inner join 
second table b 
on a.id=b.id
except
select * from a),

d as (
  select * from a
  union
  select * from b
),
c as(
select distinct a.id
from a inner join 
third table b 
on a.id=b.id
except
select * from d)

select count(*) as count from a
union
select count(*) as count from b
union 
select count(*)  as count from c

在这里,我从a和B得到正确的count,但是从c,如果我单独执行第一个连接查询,count是78471355,单独从d得到的count()是32579307,当我手动减去时,我得到的答案是45892048。但是对于查询“select count()as count from c”,我得到的输出是48762978。
请注意,我在presto db中执行此操作,并且我也有第四个表来查找计数。我没有添加它,因为c的输出是错误的。请帮助。

ev7lccsx

ev7lccsx1#

您似乎想计算表a中的id值,这些值也出现在四个不同的表中,但按优先级顺序比较相关的表;为此,您可以使用CASE表达式来测试id是否存在于每个相关表中。

SELECT table_name,
       COUNT(*) AS num_rows
FROM   (
  SELECT id,
         CASE
         WHEN EXISTS (SELECT 1 FROM first_table t WHERE a.id = t.id)
         THEN 'first_table'
         WHEN EXISTS (SELECT 1 FROM second_table t WHERE a.id = t.id)
         THEN 'second_table'
         WHEN EXISTS (SELECT 1 FROM third_table t WHERE a.id = t.id)
         THEN 'third_table'
         WHEN EXISTS (SELECT 1 FROM fourth_table t WHERE a.id = t.id)
         THEN 'fourth_table'
         END AS table_name
  FROM   a
)
WHERE  table_name IS NOT NULL
GROUP BY table_name;

其中,对于样本数据:

CREATE TABLE a (id) AS
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 10;

CREATE TABLE first_table (id) AS
  SELECT 1 FROM DUAL UNION ALL
  SELECT 2 FROM DUAL UNION ALL
  SELECT 3 FROM DUAL;

CREATE TABLE second_table (id) AS
  SELECT 1 FROM DUAL UNION ALL
  SELECT 2 FROM DUAL UNION ALL
  SELECT 5 FROM DUAL;

CREATE TABLE third_table (id) AS
  SELECT 2 FROM DUAL UNION ALL
  SELECT 6 FROM DUAL UNION ALL
  SELECT 7 FROM DUAL;

CREATE TABLE fourth_table (id) AS
  SELECT 3 FROM DUAL UNION ALL
  SELECT 4 FROM DUAL UNION ALL
  SELECT 10 FROM DUAL;

输出:
| 表名|数量行|
| --|--|
| 第一表| 3 |
| 第四表| 2 |
| 第二表| 1 |
| 第三表| 2 |
fiddle

相关问题