查询结果不适用于PostgreSQL中的数组类型

时间:2019-04-12 07:19:25

标签: sql postgresql

我有两个表,其中包含一列带有PostgreSQL中数据类型数组的列。结构如下:

tbl_tour_packages

enter image description here

tbl_header_images

enter image description here

我有一个包含多个联接的查询。该查询可以与其他联接正常工作,并且没有显示错误。但是缺少tbl_header_images中的值。 查询是:

SELECT 
    t1.tour_id AS pid,
    t1.tour_name AS title,
    t1.tour_duration AS nights,
    t1.tour_price_full AS price,
    t1.discount AS discount,
    t1.tour_seo_title AS seo,
    t3.category AS category,
    t4.image_names[1] AS image_url,
    CASE WHEN max(s.state_name) IS NULL THEN NULL ELSE array_agg(s.state_name) END AS state,
    CASE WHEN max(o.destination) IS NULL THEN NULL ELSE array_agg(o.destination) END AS destinations
FROM tbl_tour_packages t1
    LEFT JOIN tbl_countries t2 ON t1.tour_country_iso = t2.iso
    LEFT JOIN tbl_categories t3 on t1.tour_category_id = t3.id
    LEFT JOIN tbl_header_images t4 ON t1.tour_id = t4.package_id
    LEFT JOIN tbl_states AS s ON (t1.tour_state @> array[s.state_code])
    LEFT JOIN tbl_destinations AS o ON (t1.tour_destination @> array[o.id])
WHERE t1.tour_status = 1
GROUP BY 1,7,8
ORDER BY view_count ASC LIMIT 6

我想从tbl_header_images中获取“ image_name”。任何快速帮助或建议,将不胜感激。

1 个答案:

答案 0 :(得分:0)

在WHERE子句之前,您应该可以执行以下操作:

, unnest(image_names) _image_names

,然后在select语句中将其聚合回数组

array_agg(_image_names) AS image_names

我不太愿意尝试t4.image_names[1] AS image_url,但是我敢肯定您可以从这里进行尝试。

因此整个查询将类似于:

编辑:我去除了额外的分组

SELECT 
    t1.tour_id AS pid,
    t1.tour_name AS title,
    t1.tour_duration AS nights,
    t1.tour_price_full AS price,
    t1.discount AS discount,
    t1.tour_seo_title AS seo,
    t3.category AS category,
    (array_agg(_image_names))[1] AS image_url,
    CASE WHEN max(s.state_name) IS NULL THEN NULL ELSE array_agg(s.state_name) END AS state,
    CASE WHEN max(o.destination) IS NULL THEN NULL ELSE array_agg(o.destination) END AS destinations
FROM tbl_tour_packages t1
    LEFT JOIN tbl_countries t2 ON t1.tour_country_iso = t2.iso
    LEFT JOIN tbl_categories t3 on t1.tour_category_id = t3.id
    LEFT JOIN tbl_header_images t4 ON t1.tour_id = t4.package_id
    LEFT JOIN tbl_states AS s ON (t1.tour_state @> array[s.state_code])
    LEFT JOIN tbl_destinations AS o ON (t1.tour_destination @> array[o.id])
    , unnest(t4.image_names) AS _image_names
WHERE t1.tour_status = 1
GROUP BY 1,7
ORDER BY view_count ASC LIMIT 6

或者我会选择subselect:

SELECT t1.*,
    (SELECT image_names[1] FROM tbl_header_images WHERE package_id = t1.tour_id) AS image_url
FROM t1, t2, t3
WHERE ...