这是简化的等价物:
桌子: user_log
领域: log_id, user_id, log_comment, log_created, log_updated
我尝试过:
SELECT * FROM user_log
WHERE user_id = 123
AND log_comment = "The one I want"
AND NOT log_comment = "The one I don't want"
期望的结果: 理想情况下,我希望它返回该用户 ID 表中的所有记录,如果它包含"我不想要的那个"的注释,则根本不返回任何记录。
实际结果: 不行。相反,它的作用是返回带有注释"我想要的那个"的记录。
抱歉,如果标题中不清楚,我不确定如何描述我的问题。
我会使用NOT EXISTS
:
SELECT ul.*
FROM user_log ul
WHERE NOT EXISTS (SELECT 1
FROM user_log ul1
WHERE ul.user_id = ul1.user_id AND ul1.log_comment = "The one I don't want"
);
- 您可以使用
Group By
和Having
子句使用基于条件聚合函数的筛选。在派生表中,我们可以确定user_id = 123
是否有任何带有log_comment = "The one I don't want"
的行。 HAVING NOT SUM(log_comment = "The one I don't want")
确保user_id不存在此类行。- 现在,只需将此派生表结果集联接到
user_log
表,并仅获取log_comment = "The one I want"
的那些行。 - 如果user_id甚至有一行带有"我不想要的那个";此查询将不会返回任何单行。
将条件聚合与分组依据结合使用:
SELECT u1.*
FROM user_log AS u1
JOIN (SELECT u2.user_id
FROM user_log AS u2
WHERE u2.user_id = 123
GROUP BY u2.user_id
HAVING NOT SUM(u2.log_comment = "The one I don't want")
) AS dt ON dt.user_id = u1.user_id
WHERE
u1.log_comment = "The one I want"
我会使用exists
和not exists
:
select ul.*
from user_log ul
where exists (select 1
from user_log ul2
where ul2.user_id = ul.user_id and
ul2.comment = 'The one I want'
) and
not exists (select 1
from user_log ul2
where ul2.user_id = ul.user_id and
ul2.comment = 'The one I don''t want'
) ;
SELECT * FROM user_log
WHERE user_id = 123
AND log_comment LIKE "%The one I want%"
AND log_comment NOT LIKE "%The one I don't want%"
当我阅读您的描述时,这里有一些log_comment
示例
"嘿,我想要的那个——是的!" -- 捕捉这个"嘿,我想要的那个 -- 是的,我想要的那个
" -- 捕捉这个
"嘿,我不想要的那个 -- 是的!" --跳过这个
"嘿,我想要的那个。 哦,等一下 我不想要的那个" -- 跳过这个
"我不想要的那个 哦,等等 -- 我想要的那个" -- 也跳过了
如果这些结果不正确,请用一组示例来澄清您的问题。
我不确定我是否理解这个问题,但这会起作用吗:
SELECT * FROM user_log
WHERE user_id = 123
AND log_comment not like "%The one I don't want%"