经过几个小时的搜索,我终于放弃并寻求帮助。我发现了一些让我接近的东西,但似乎没有正常工作。
基本上寻找在3-6个月前使用我们但在过去3个月内没有使用过我们的用户。
为了举例说明,我有两个名为event(id,clientFK,insertion_date,officeFK)和client(id,name)的表:
SELECT DISTINCT e.id, e.insertion_date, c.name
FROM event e
LEFT JOIN client c ON c.id = e.clientFK
WHERE e.id NOT IN (
SELECT e.id
FROM event e
WHERE e.insertion_date
BETWEEN (
NOW( ) - INTERVAL 3
MONTH
)
AND NOW( )
)
AND e.insertion_date > ( NOW( ) - INTERVAL 6
MONTH )
AND officeFK =1
ORDER BY e.insertion_date DESC
的 的 ** *** UPDATE id只是一个自动递增列,所以显然它永远不会出现使用上面的逻辑。我打算在事件表中搜索clientFK。根据下面的第一个回复,我想出了这个:
SELECT DISTINCT e.clientFK, e.insertion_date, c.name
FROM event e
LEFT JOIN client c ON c.id = e.clientFK
WHERE e.clientFK NOT IN (
SELECT e.clientFK FROM event e
WHERE e.insertion_date > (NOW() - INTERVAL 3 DAY)
)
AND e.insertion_date BETWEEN (NOW() - INTERVAL 3 DAY) AND (NOW() - INTERVAL 6 MONTH)
AND officeFK =1
ORDER BY e.insertion_date DESC
但是,即使将NOT IN子查询缩小到仅3天,我仍然会返回0行。将NOT IN更改为IN也会导致返回0行。我的事件表中有数千行,其中clientFK在过去3天内“不在”。我必须在某处做错事。
以下正确代码:
SELECT DISTINCT e.id, e.insertion_date, c.name
FROM event e
JOIN client c ON c.id = e.clientFK
WHERE e.clientFK NOT IN (
SELECT e.clientFK FROM event e
WHERE e.insertion_date > (NOW() - INTERVAL 3 MONTH)
)
AND e.insertion_date < (NOW() - INTERVAL 3 MONTH)
AND insertion_date > (NOW() - INTERVAL 6 MONTH)
AND e.officeFK = 1
ORDER BY e.insertion_date DESC
答案 0 :(得分:1)
有几种方法可以做到这一点。但我觉得你很亲密。您的主查询中似乎没有3-6个月的日期范围。从6个月到现在,你正在检查任何事情。这与OP的用户规格不符 - 3-6个月前的事件用户,但不是在过去3个月内。从逻辑上看它似乎是一样的,但试试这个。
SELECT DISTINCT e.id, e.insertion_date, c.name
FROM event e
JOIN client c ON c.id = e.clientFK
WHERE e.clientFK NOT IN (
SELECT e.clientFK FROM event e
WHERE e.insertion_date > (NOW() - INTERVAL 3 MONTH)
)
AND e.insertion_date BETWEEN (NOW() - INTERVAL 3 MONTH) AND (NOW() - INTERVAL 6 MONTH)
AND e.officeFK = 1
ORDER BY e.insertion_date DESC