如何在查询

时间:2017-01-09 11:33:45

标签: mysql

我想使用以下查询从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 | +----+---------+---------+

1 个答案:

答案 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')