我想使用以下查询从posts
表中检索结果。我想选择帖子,其中语句的where部分中的两个条件都通过了。
术语类型是类别并且在CategoryTest中
AND,其中术语类型为标记,位于TagTest
WHERE IN
条件目前包含一个元素,但可能更多。 两者 WHERE
如果未显示另一个,则会给出结果。 所以每个人单独工作或OR
也可以工作。它会回复同一个帖子,ID为33 - 所以我认为WHERE组没有正确设置。
SELECT `posts`.*
FROM `posts`
LEFT JOIN `post_term` ON `posts`.`id` = `post_term`.`post_id`
LEFT JOIN `terms` ON `terms`.`id`= `post_term`.`term_id`
LEFT JOIN `meta` ON `meta`.`post_id` = `posts`.`id`
WHERE (
`terms`.`type` = 'category'
AND `terms`.`name` IN('CategoryTest')
)
AND (
`terms`.`type` = 'tag'
AND `terms`.`name` IN('TagTest')
)
表定义:
条款表
+----+--------------+--------------+----------+
| id | name | slug | type |
+----+--------------+--------------+----------+
| 31 | CategoryTest | CategoryTest | category |
| 32 | TagTest | TagTest | tag |
+----+--------------+--------------+----------+
帖子表:
+----+-------+---------+---------+-----------+------------+------------+
| id | title | content | user_id | parent_id | created_at | updated_at |
+----+-------+---------+---------+-----------+------------+------------+
| 33 | HEllo | | 0 | 0 | NULL | NULL |
+----+-------+---------+---------+-----------+------------+------------+
post_term
+----+---------+---------+
| id | post_id | term_id |
+----+---------+---------+
| 73 | 33 | 31 |
| 74 | 33 | 32 |
+----+---------+---------+
答案 0 :(得分:1)
您只需查看exists
:
select * from posts p
where
exists(select * from post_term pt join Terms t on pt.term_id = t.id
where pt.post_id = p.id and t.name = 'category') and
exists(select * from post_term pt join Terms t on pt.term_id = t.id
where pt.post_id = p.id and t.name = 'tag')