在SQL中使用AND和括号分组不起作用

时间:2021-01-10 作者:Collizo4sky

我试图在一个查询中组合两个条件,但它不起作用。但独立运行这些条件是可行的。

让我解释一下。运行此查询时:

SELECT DISTINCT
    SQL_CALC_FOUND_ROWS wp_users.*
FROM
    wp_users
    INNER JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id)
WHERE
    (wp_users.user_login LIKE \'%little%\'
        OR wp_users.user_email LIKE \'%little%\'
        OR wp_users.user_url LIKE \'%little%\'
        OR wp_users.display_name LIKE \'%little%\'
        OR (wp_usermeta.meta_key = \'first_name\'
            AND wp_usermeta.meta_value LIKE \'%little%\')
        OR (wp_usermeta.meta_key = \'last_name\'
            AND wp_usermeta.meta_value LIKE \'%little%\'))
ORDER BY
    user_registered DESC
我得到这个结果

当我运行这个

SELECT DISTINCT
    SQL_CALC_FOUND_ROWS wp_users.*
FROM
    wp_users
    INNER JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id)
WHERE ((wp_usermeta.meta_key = \'car_type\'
        AND wp_usermeta.meta_value LIKE \'%Camry%\')
    OR(wp_usermeta.meta_key = \'car_type\'
        AND wp_usermeta.meta_value LIKE \'%Toyota%\'))
ORDER BY
    user_registered DESC
我得到这个结果

enter image description here

如您所见,ID为46的用户在两个查询结果中都很常见。

我只想显示匹配这两个查询条件的用户。在这种情况下,仅使用用户ID 46。

当我这样组合它们时,我什么也得不到:

SELECT DISTINCT
    SQL_CALC_FOUND_ROWS wp_users.*
FROM
    wp_users
    INNER JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id)
WHERE
    (wp_users.user_login LIKE \'%little%\'
        OR wp_users.user_email LIKE \'%little%\'
        OR wp_users.user_url LIKE \'%little%\'
        OR wp_users.display_name LIKE \'%little%\'
        OR (wp_usermeta.meta_key = \'first_name\'
            AND wp_usermeta.meta_value LIKE \'%little%\')
        OR (wp_usermeta.meta_key = \'last_name\'
            AND wp_usermeta.meta_value LIKE \'%little%\'))
            
AND((wp_usermeta.meta_key = \'car_type\'
    AND wp_usermeta.meta_value LIKE \'%Camry%\')
    OR(wp_usermeta.meta_key = \'car_type\'
        AND wp_usermeta.meta_value LIKE \'%Toyota%\'))
ORDER BY
    user_registered DESC

enter image description here

这已经让我发疯好几个小时了。请帮我找出问题所在。

1 个回复
最合适的回答,由SO网友:Tim Jensen 整理而成

您需要2个表联接,因为WHERE子句中实际上有2个元键:

SELECT DISTINCT
    SQL_CALC_FOUND_ROWS wp_users.*
FROM
    wp_users
        INNER JOIN wp_usermeta AS um1 ON (wp_users.ID = um1.user_id)
        INNER JOIN wp_usermeta AS um2 ON (wp_users.ID = um2.user_id)
WHERE
    (wp_users.user_login LIKE \'%little%\'
        OR wp_users.user_email LIKE \'%little%\'
        OR wp_users.user_url LIKE \'%little%\'
        OR wp_users.display_name LIKE \'%little%\'
        OR (um1.meta_key = \'first_name\'
            AND um1.meta_value LIKE \'%little%\')
        OR (um1.meta_key = \'last_name\'
            AND um1.meta_value LIKE \'%little%\'))

  AND((um2.meta_key = \'car_type\'
    AND um2.meta_value LIKE \'%Camry%\')
    OR(um2.meta_key = \'car_type\'
        AND um2.meta_value LIKE \'%Toyota%\'))
ORDER BY
    user_registered DESC