从一个表的列中查询2个值并加入另一个表?

时间:2017-09-26 05:37:13

标签: postgresql

我目前在其他人使用的视图中查询两个表。我已经尝试了几种不同的方法来构建查询,但我得到的最佳时间是在10到15分钟之间返回值。查询是:

SELECT a.unit_location_id, a.location_name, a.serial_number, a.unit_name,
a.rating, b.max_number, c.min_number

FROM details a

JOIN (SELECT serial_number, setting_value AS max_number
FROM settings WHERE setting_name = 'max number') b ON a.serial_number = b.serial_number

JOIN (SELECT serial_number, setting_value AS min_number
FROM settings WHERE setting_name = 'min number') c ON a.serial_number = c.serial_number

WHERE b.max = c.min;

任何想法都可以加快查询速度,或者我错过了什么?

2 个答案:

答案 0 :(得分:2)

如果你可以消除这两个连接中的一个,那么我可能会立即显着改善性能。通过使用单个聚合查询,我们可以在settings表中实际识别每个序列号的最大和最小数字。在下面的查询中,我将details加入到一个查找最大和最小数字的子查询中。

SELECT
    a.unit_location_id,
    a.location_name,
    a.serial_number,
    a.unit_name,
    a.rating,
    t.max_number,
    t.min_number
FROM details a
INNER JOIN
(
    SELECT
        serial_number,
        MAX(CASE WHEN setting_name = 'max number' THEN setting_value END) AS max_number,
        MAX(CASE WHEN setting_name = 'min number' THEN setting_value END) AS min_number
    FROM settings
    GROUP BY serial_number
) t
    ON a.serial_number = t.serial_number
WHERE
    t.max_number = t.min_number;

答案 1 :(得分:0)

我使用" WITH"找到了解决方案。时间从10分钟到15分钟不到一分钟。大多数时间都不到30秒。

WITH settings AS (
     SELECT serial_number, 
            CASE WHEN setting_name = 'max number' THEN setting_value END AS max_number,
            CASE WHEN setting_name = 'min number' THEN setting_value END AS min_number
     FROM settings
     WHERE setting_name IN ('max number', 'min number'))

SELECT a.unit_location_id, a.location_name, a.serial_number, a.unit_name,
       a.rating, b.setting_value AS min_number, c.setting_value AS max_number 
FROM details a
LEFT JOIN settings b ON a.serial_number = b.serial_number 
         AND max_number IS NOT NULL
LEFT JOIN settings c ON a.serial_number = c.serial_number 
         AND max_number IS NOT NULL