PostgreSQL匹配id的列表

时间:2013-01-23 08:52:13

标签: arrays postgresql

我正在扩展我选择的media个项目,其中包含一些过滤器category。媒体和类别之间的关系是多对多的,这表明我有一个关系表media_categories。我正在以integer[]的形式发送带有类别ID的类别过滤器。 如何匹配两个数组以获取公共元素?

这是我的存储过程: (见代码中的评论)

CREATE OR REPLACE FUNCTION mediabase.select_media(sysenvironment character varying, statusid integer, wildcard character varying, categoryIds integer[])
  RETURNS refcursor AS
$BODY$
    DECLARE ref refcursor;

    BEGIN
      OPEN ref FOR 

    SELECT 
        media.id, 
        media.title, 
        media.unique_filename, 
        media.owner_id, 
        media.status_id, 
        media.location_name_id, 
        media.upload_user_id, 
        media.upload_ip, 
        media.metadata_id, 
        media.type_id, 
        media.description, 
        media.system_environment, 
        media.upload_date, 
        media.gps_location, 
        media.language_id, 
        (SELECT ARRAY (SELECT publication_id FROM mediabase.media_publications WHERE media_id = media.id)) as publication_ids,
        media.limitations, 
        (SELECT ARRAY (SELECT category_id FROM mediabase.media_categories WHERE media_id = media.id)) as category_ids,
        (SELECT ARRAY (SELECT keyword_id FROM mediabase.media_keywords WHERE media_id = media.id)) as keyword_ids,
        media.credits,
        metadata.width, 
        metadata.height, 
        metadata.equipment, 
        metadata.copyright, 
        metadata.creation_time, 
        metadata.file_format, 
        metadata.resolution, 
        metadata.resolution_unit, 
        metadata.gps_longitude, 
        metadata.gps_latitude, 
        metadata.artist, 
        metadata.color_space, 
        metadata.gps_altitude, 
        metadata.software_used, 
        metadata.user_comment
    FROM 
        mediabase.media, 
        mediabase.metadata
    WHERE media.metadata_id = metadata.id
    AND (media.status_Id = statusId OR statusId = -1)
    AND media.system_environment = sysEnvironment
    AND (lower(media.title) LIKE lower('%'||lower(wildcard)||'%') OR lower(media.description) LIKE lower('%'||lower(wildcard)||'%') OR lower(metadata.artist) LIKE lower('%'||lower(wildcard)||'%'))
    -- Problem start
    -- in the following line I'm trying to make the match with no success
    AND (SELECT ARRAY (SELECT category_id FROM mediabase.media_categories WHERE media_id = media.id)) IN (categoryIds) 
    -- Problem end
    ORDER BY media.upload_date DESC;

      RETURN ref;                       
    END;
    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

由于

1 个答案:

答案 0 :(得分:1)

嗯,我猜你正在寻找postgre数组函数< @(包含在)

http://www.postgresql.org/docs/9.2/static/functions-array.html

条件必须类似于:

AND (SELECT ARRAY (SELECT category_id FROM mediabase.media_categories WHERE media_id = media.id)) <@ categoryIds