OR子句后的AND子句

时间:2014-11-04 08:30:04

标签: mysql

我正在尝试运行一个带有“FIND_IN_SET”的MySQL查询。

运行查询有效,但我还需要找到“user_optin”,它等于1。

运行此查询当前会找到user_optin为“0”的人

SELECT `user_id`, `user_firstname`, `user_surname`, `user_email`, `user_type`, `user_optin`
FROM (`users`)
WHERE `user_type` =  'Volunteer'
AND 1 <=FIND_IN_SET(1, user_interests)
OR 1 <=FIND_IN_SET(2, user_interests)
OR 1 <=FIND_IN_SET(5, user_interests)
OR 1 <=FIND_IN_SET(6, user_interests)
OR 1 <=FIND_IN_SET(7, user_interests)
OR 1 <=FIND_IN_SET(8, user_interests)
OR 1 <=FIND_IN_SET(10, user_interests)
AND 1 <=FIND_IN_SET(1, user_activities)
OR 1 <=FIND_IN_SET(2, user_activities)
OR 1 <=FIND_IN_SET(4, user_activities)
OR 1 <=FIND_IN_SET(5, user_activities)
OR 1 <=FIND_IN_SET(11, user_activities)
OR 1 <=FIND_IN_SET(12, user_activities)
OR 1 <=FIND_IN_SET(14, user_activities)
AND `user_optin` =  '1'

如果我从查询中取出“OR”,则查询的user_optin部分可以正常工作。

无论如何,我可以让user_optin显示找到“1”条目,而不是“0”条目。

我没有设计这个数据库,我发现find_in_set不是MySQL数据库查询的最佳方法。

干杯

1 个答案:

答案 0 :(得分:1)

()中添加其他条款,将它们与最终的AND分开。

SELECT
    `user_id`,
    `user_firstname`,
    `user_surname`,
    `user_email`,
    `user_type`,
    `user_optin`
FROM
    (`users`)
WHERE
    (
        `user_type` = 'Volunteer'
        AND 1 <= FIND_IN_SET(1, user_interests)
        OR 1 <= FIND_IN_SET(2, user_interests)
        OR 1 <= FIND_IN_SET(5, user_interests)
        OR 1 <= FIND_IN_SET(6, user_interests)
        OR 1 <= FIND_IN_SET(7, user_interests)
        OR 1 <= FIND_IN_SET(8, user_interests)
        OR 1 <= FIND_IN_SET(10, user_interests)
        AND 1 <= FIND_IN_SET(1, user_activities)
        OR 1 <= FIND_IN_SET(2, user_activities)
        OR 1 <= FIND_IN_SET(4, user_activities)
        OR 1 <= FIND_IN_SET(5, user_activities)
        OR 1 <= FIND_IN_SET(11, user_activities)
        OR 1 <= FIND_IN_SET(12, user_activities)
        OR 1 <= FIND_IN_SET(14, user_activities)
    )
AND `user_optin` = '1'