0

我将多个表加入到一个查询中。我需要对 IN 语句中的值进行部分匹配。这是一个例子。

SELECT DISTINCT 
    am.id AS id, 
    am.flagged AS flagged, 
    am.name AS name, 
    am.type AS type, 
    am.file AS file, 
    am.s3_tag AS s3_tag, 
    am.low_s3_tag AS low_s3_tag 
FROM accounts_media am 
    LEFT JOIN accounts_location_media alm ON am.id = alm.media_id 
    LEFT JOIN accounts_location al ON al.id = alm.location_id 
    LEFT JOIN accounts_person_media apm ON am.id = apm.media_id 
    LEFT JOIN accounts_person ap ON ap.id = apm.person_id 
    LEFT JOIN accounts_event_media_record aemr ON am.id=aemr.media_id 
    LEFT JOIN accounts_medianote_media_record amma ON am.id=amma.media_id 
    LEFT JOIN accounts_medianote amn ON amma.medianote_id=amn.id 
WHERE 
    am.account_id = '1234' 
    AND am.flagged = FALSE 
    AND ('Da' IN (SELECT first_name FROM accounts_person WHERE account_id = '1234') 
    AND ('Rob' IN (SELECT first_name FROM accounts_person WHERE account_id = '1234') 

在里面

AND ('Da' IN (SELECT first_name FROM accounts_person WHERE account_id = '1234')

声明表中有表示“Dan”、“Daniel”等的值。还有“Rob”和“Robert”。我需要该语句来确保包含“Da”的名称以及该表中包含“Rob”的任何名称。有没有办法做到这一点?

因此,一条记录可以链接到 accounts_person 表中的多个人。所以可以说我有三个记录。

记录一:记录附有一个名叫丹的人。

记录二:记录附有一个名叫罗伯特的人。

记录三:记录附有一个叫丹和一个叫罗伯特的人。

我希望查询只返回记录三,因为它具有“Da”和“Rob”的匹配项。

4

2 回答 2

3

尝试这个:

WHERE 
    am.account_id = '1234' 
    AND am.flagged = FALSE 
    -- AND ( ap.first_name LIKE '%Da%' OR ap.first_name LIKE '%Rob%')
    AND EXISTS 
        ( SELECT 1
            FROM accounts_person apx
           WHERE apx.first_name LIKE '%Da%'
             AND apx.account_id = am.account_id
        )
    AND EXISTS 
        ( SELECT 1
            FROM accounts_person apy
           WHERE apy.first_name LIKE '%Rob%'
             AND apy.account_id = am.account_id
        )
于 2013-02-21T04:26:34.400 回答
1

我不确定,但我认为你想要一个类似的声明,在 Da 之后有一个外卡。

SELECT DISTINCT 
    am.id AS id, 
    am.flagged AS flagged, 
    am.name AS name, 
    am.type AS type, 
    am.file AS file, 
    am.s3_tag AS s3_tag, 
    am.low_s3_tag AS low_s3_tag 
FROM accounts_media am 
    LEFT JOIN accounts_location_media alm ON am.id = alm.media_id 
    LEFT JOIN accounts_location al ON al.id = alm.location_id 
    LEFT JOIN accounts_person_media apm ON am.id = apm.media_id 
    LEFT JOIN accounts_person ap ON ap.id = apm.person_id 
    LEFT JOIN accounts_event_media_record aemr ON am.id=aemr.media_id 
    LEFT JOIN accounts_medianote_media_record amma ON am.id=amma.media_id 
    LEFT JOIN accounts_medianote amn ON amma.medianote_id=amn.id 
WHERE 
    am.account_id = '1234' 
    AND am.flagged = FALSE 
    AND (accounts_person.first_name like '%Da%'
    OR accounts_person.first_name like '%Rob%') 
    AND accounts_person.account_id = '1234'
于 2013-02-21T02:59:08.840 回答