我有8个主表,每个表有大约60万条记录。
我们说表名是
type_11_14
type_12_15
type_13_16
type_4_5
type_6
type_7
type_8
type_10
每个表都有代码和名称列。 代码是主键。 我无法组合所有这些表并制作一个表。
在上表中, type_11_14 包含类型11和14条记录 type_7 有7类记录
我有其他表 all_types_count 。它具有上述类型的计数信息。 对于给定的类型和代码列表(我们给出的最大代码为50),我需要获取其名称,类型,代码和计数
我用UNION编写了以下查询。查询运行正常。但如果我运行解释计划,我会得到
错误 无法启用约束。一行或多行包含违反非空,唯一或外键约束的值。
再次在下面的查询中我查询 all_types_count 表8次。而不是我想到从 all_types_count 首先获取所有记录,然后离开加入主表以获得所需的结果..
不确定什么是最好的SQL查询解决方案。有人可以为我提供最好的方法吗?
SELECT type,code,total_count,type_11_14.name
FROM all_types_count,type_11_14
WHERE all_types_count.type in (11,14)
AND all_types_count.code=type_11_14.code
AND all_types_count.code in ( 3456,6789)
UNION ALL
SELECT type,code,total_count,type_12_15.name
FROM all_types_count,type_12_15
WHERE all_types_count.type in (12,15)
AND all_types_count.code=type_12_15.code
AND all_types_count.code in ( 2345,9087,234)
UNION ALL
SELECT type,code,total_count,type_13_16.name
FROM all_types_count,type_13_16
WHERE all_types_count.type in (13,16)
AND all_types_count.code=type_13_16.code
AND all_types_count.code in ( 98,24)
UNION ALL
SELECT type,code,total_count,type_4_5.name
FROM all_types_count,type_4_5
WHERE all_types_count.type in (4,5)
AND all_types_count.code=type_4_5.code
AND all_types_count.code in ( 765,9087,3456)
UNION ALL
SELECT type,code,total_count,type_6.name
FROM all_types_count,type_6
WHERE all_types_count.type=6
AND all_types_count.code=type_6.code
AND all_types_count.code in ( 5563,323,434,3442)
UNION ALL
SELECT type,code,total_count,type_7.name
FROM all_types_count,type_7
WHERE all_types_count.type=7
AND all_types_count.code=type_7.code
AND all_types_count.code in ( 7887,313,23,32,21)
UNION ALL
SELECT type,code,total_count,type_8.name
FROM all_types_count,type_8
WHERE all_types_count.type=8
AND all_types_count.code=type_8.code
AND all_types_count.code in ( 9988,1221)
UNION ALL
SELECT type,code,total_count,type_10.name
FROM all_types_count,type_10
WHERE all_types_count.type=10
AND all_types_count.code=type_10.code
AND all_types_count.code in ( 7787,23213)
谢谢
基兰
答案 0 :(得分:1)
如果您的查询被写为:
,那么查询应该更有效率SELECT type,code,total_count,type_11_14.name
FROM all_types_count
left outer join type_11_14
on all_types_count.type in (11,14)
and all_types_count.code=type_11_14.code
and all_types_count.code in ( 3456,6789)
left outer join type_12_15
on all_types_count.type in (12,15)
and all_types_count.code=type_12_15.code
and all_types_count.code in ( 2345,9087,234)
left outer join . . .
如果您不熟悉连接/左外连接/右外连接/交叉连接语法,那么您应该学习它。
在原始查询中,优化器很可能会为每个子查询读取一次all_types_count表。使用联接,它应该只读取一次,在需要时加入其他表。