如何在MySQL中的IN语句中进行部分匹配

时间:2013-02-21 02:57:19

标签: mysql

我将多个表连接到一个查询中。我需要在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表中的多个人。所以我要说我有三个记录。

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

记录二:名为罗伯特的人附在记录上。

记录三:一个名叫丹的人和一个名叫罗伯特的人被记录在案。

我希望查询只返回Record Three,因为它匹配'Da'和'Rob'。

2 个答案:

答案 0 :(得分: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
        )

答案 1 :(得分: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'