我有两个表:posts和post_data,posts有一个id,post_data通过post_id列链接到posts,结构如下:
Posts
id
name
Post_Data
id
post_id
Value
好的,现在我在 post 表中有一些条目,在 post_data 表中有一些条目 post_data 表条目如下所示:
id: 1
post_id:1001
value: test
id:2
post_id:1001
value: hello
id:3
post_id:1002
value: test
我需要帮助编写一个查询,该查询只会返回 post_data 为“hello”和“test”的帖子。我知道如何编写查询来 reutrn 任何 post_data 为“hello”或“test”的帖子,但我似乎不知道如何编写只返回同时包含“hello”和“test”的帖子的查询
提前致谢:)
只需查看每组 post_data 行,并在分组后的having子句中使用聚合函数检查您的值。
select post_id
from post_data
group by 1
having sum(value="hello")
and sum(value="test")
您可以进行 2 次连接,以便将 2 个条件放在 where 中
SELECT distinct(p.id) FROM posts as p left join post_data as pd1 on p.id = pd1.post_id left join post_data as pd2 on pd1.post_id = pd2.post_id where pd1.value = "hello" and pd2.value = "test"
这样就可以了。
注意:我有点担心性能,因为根据您的数据库,这将创建一个非常大的数据集(
joins
构建数据集,然后我们可以使用where
进行过滤)我知道这只是一个示例,因此我不会深入研究您的示例,但改进此示例的方法是重新审视架构的基础和设计。