概览
我正在简化我的应用程序的描述以使查询更清晰。该应用程序存储保存的短语
。这些短语各自分配了一个类别
。 用户
可以发布
这些短语。我的查询的英文描述:
I need to pass a
category
anduser
into theprepared statement
. The result will include onlyphrases
with thecategory
passed as an argument. From thephrases
of thiscategory
, onlyphrases
will be returned where there does not exist any posted instances of thisphrase
for theuser
argument with thetimePosted
field in the last two weeks.
最小模式
保存的短语
- phraseIdentifier - INT UNSIGNED
- textContent - VARCHAR
- 相关类别 - VARCHAR
- ___主键是短语标识符
postedPhrase
- savedPhrase - INT UNSIGNED - 外键引用 savedPhrase(phraseIdentifier)
- 用户名 - VARCHAR
- timeReposted - 时间戳
- ___主键是所有列出字段的组合
当前最佳行为尝试
我是自学/学习 MySQL 的,并且相信我在 joins
方面遇到了困难。我想我应该使用至少一个 left outer join
如下图所示。左表将是 savedPhrase
,右表将是 postedPhrase
。
SELECT * FROM savedPhrase S
LEFT JOIN postedPhrase P
ON (S.phraseIdentifier = P.savedPhrase AND P.username = ?)
WHERE
(P.savedPhrase IS NULL OR P.timeReposted < DATE_SUB(NOW(), INTERVAL 14 day)) AND
S.associatedCategory = ?
上面的查询几乎有效。但是,一旦单个 postedPhrase
行至少在两周前存在,它将返回加入的 savedPhrase
,即使一个已经在同一帐户上以相同的标识符 less 发布比两周前。
进一步讨论
我遇到困难的地方是“缺席条件”。这是过去两周内不得存在 savedPhrase
的位置。在上一段中,我解释了缺席是如何不起作用的,因为 postedPhrase
是根据它们自己独立的 timeReposted
返回的。看来我应该将缺席条件添加到左外连接的右圆中。简化何时将条件应用于 ON
与 WHERE
将非常有帮助。
我已经解决这个问题一段时间了,如果有任何指示,我将不胜感激。如果我可以包含任何其他信息,请告诉我。
最佳答案
您不必使用JOIN 来存档您想要的结果。 您可以根据您的问题中描述的查询的英文描述来编写查询。
SELECT S.*
FROM savedPhrase S
WHERE S.associatedCategory = ?
AND NOT EXISTS (SELECT 1
FROM postedPhrase P
WHERE P.username = ?
AND S.phraseIdentifier = P.savedPhrase
AND P.timeReposted >= DATE_SUB(NOW(),
INTERVAL 14 day))
关于MySQL Left Outer Join with Absence 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041630/