在我的表 plin_korisnik 中,我有字段活动,它被定义为布尔类型。
我正在尝试执行此查询以从该表和另外两个表中获取数据:
SELECT
pk.omm AS omm,
pk.br_plin AS br_plin,
pk.naziv AS naziv,
pk.ulica||' '||pk.kbr AS adresa,
pk.pu||' - '||pk.naziv_pu AS mjesto,
po.datum AS datum,
CASE WHEN po.stanje >= 999999 THEN NULL ELSE po.stanje END AS stanje,
po.napomena AS napomena,
po.plin_postar AS laus,
pp.ime||' '||pp.prezime AS postar
FROM plin_korisnik pk
INNER JOIN
plin_ocitanje po ON pk.omm = po.omm
INNER JOIN plin_postar pp ON pp.laus = po.plin_postar
WHERE po.datum>='2017-01-26'
AND po.datum<='2017-01-26'
AND pk.tip='p'
AND pk.active = TRUE
ORDER BY po.datum, pk.naziv
但是查询需要很长时间(就像永远;我在半小时后中断了它),但是当我从WHERE子句中删除 pk.active = TRUE 测试时,查询以预期的速度执行。我曾尝试将布尔类型转换为整数,但问题仍然存在。
如果有人能解释如何在此查询和类似查询中使用布尔字段,我将不胜感激。 有效字段未编入索引,也许应该是,请帮助。
编辑: 经过几个小时的思考后,我推出了使用WITH子句的解决方案:
WITH pk AS (
SELECT * FROM plin_korisnik WHERE active AND tip='p'
)
SELECT
pk.omm AS omm,
pk.br_plin AS br_plin,
pk.naziv AS naziv,
pk.ulica||' '||pk.kbr AS adresa,
pk.pu||' - '||pk.naziv_pu AS mjesto,
po.datum AS datum,
CASE WHEN po.stanje >= 999999 THEN NULL ELSE po.stanje END AS stanje,
po.napomena AS napomena,
po.plin_postar AS laus,
pp.ime||' '||pp.prezime AS postar
FROM pk
INNER JOIN
plin_ocitanje po ON pk.omm = po.omm
INNER JOIN plin_postar pp ON pp.laus = po.plin_postar
WHERE po.datum>='2017-01-26'
AND po.datum<='2017-01-26'
ORDER BY po.datum, pk.naziv;
答案 0 :(得分:1)
我认为如果你改变where子句中的顺序,从初始表开始,你可以加快速度。 关于pk.active和po.datum的索引绝对会有所帮助。 您可能需要考虑将po.datum放在内连接中,而不是放在哪里。
po.datum>='2017-01-26'
AND po.datum<='2017-01-26'
AND pk.tip='p'
AND pk.active = TRUE
将是:
pk.active = TRUE
AND pk.tip='p'
AND po.datum>='2017-01-26'
AND po.datum<='2017-01-26'