刚开始是想通过UNION ALL的连接实现数据查询,由于默认值没设置成功。就分别从数据库中查出不同的数据,在代码里面进行各种复杂的拼装,后来发现测试数据就几十万条,加载运行耗时特别长显然不合理。
后来发现通过SQL创建一个视图就行了。如下:
SELECT lr.id,
lu.camera_id,
tag.group_type AS device_type,
CASE
WHEN (lr.person_type IS NULL) THEN 'unknow'::character varying
ELSE lr.person_type
END AS person_type,
lu.upload_date,
lu.address,
lu.source,
lr.result,
'0'::character varying AS is_report
FROM ((log_table_result lr
LEFT JOIN log_table_upload lu ON (((lu.serial_id)::text = (lr.serial_id)::text)))
LEFT JOIN t_aicamera_group tag ON (((lu.group_id)::text = ((tag.group_id)::character varying)::text)))
WHERE (tag.status <> '2'::bpchar)
UNION ALL
SELECT prm.mac_id AS id,
prl.patrol_device_id AS camera_id,
'car'::character varying AS device_type,
'mac'::character varying AS person_type,
prm.create_time AS upload_date,
prlo.location_value AS address,
''::text AS source,
prm.mac_key_value AS result,
'1'::character varying AS is_report
FROM ((p_report_videomac prm
LEFT JOIN p_report_list prl ON (((prm.patrol_id)::text = (prl.patrol_id)::text)))
LEFT JOIN p_report_location prlo ON (((prm.location_id)::text = (prlo.location_id)::text)))
补充:
一、UNION 和 UNION ALL 合并查询的用法
1:语法(相同):都是将两个结果集合并
[SQL 语句 1]
UNION ALL/UNION
[SQL 语句 2]
2:UNION 做了筛选重复记录,因此效率低
UNION ALL 不做去重,故效率较高
二、SQL查询的结果某个字段是Null,用默认的值代替
语法如下:
select case when 字段名2 is null
then 替代值
else 字段名2
end as 显示字段名
from 表名
总结:当遇到查询、统计之类的任务时,可以优先考虑创建视图,union连接表查询。