sql—如何在select语句中使用表名获取不同数据库中相同表的计数?

xu3bshqb  于 2021-07-12  发布在  Spark
关注(0)|答案(1)|浏览(322)

我使用sparksql将11个表从一个数据库(db1)完全导出到另一个数据库(db2)。一旦导出完成,我就用表名比较db1和db2上每个表的计数,并检查它们是否匹配。输出列应该是,

Table_name   DB1_count   DB2_count   Match (Y/N) ?
table_1         500         500           Y
table_2         376         325           N

到目前为止,我已经能够为一个表获取第2列和第3列。但是,我不知道如何对多个表以及列1和列4实现相同的功能。

muk1a3rh

muk1a3rh1#

假设你有两张table:

t1:

DB1_count   DB2_count
500         500

t2:

DB1_count   DB2_count
376         325

可以添加“表名”列和“匹配”列,并执行联合:

select 'table_1' as Table_name,
       DB1_count, DB2_count,
       case when DB1_count = DB2_count then Y else N end as Match
from t1
union all
select 'table_2' as Table_name,
       DB1_count, DB2_count,
       case when DB1_count = DB2_count then Y else N end as Match
from t2

要动态生成查询,可以尝试:

val names = Seq(("table_1", "t1"), ("table_2", "t2"))
val query = names.map(x => s"""
select '${x._1}' as Table_name,
       DB1_count, DB2_count,
       case when DB1_count = DB2_count then Y else N end as Match
from ${x._2}
""").mkString("\nunion_all\n")

val result = spark.sql(query)

相关问题