【问题标题】:Sqlite join tables and select where column containsSqlite 连接表并选择列包含的位置
【发布时间】:2014-07-15 10:14:18
【问题描述】:

我有 3 张桌子

**Posts**

id post_title
1  First_Post
2  Second_Post
3  Third_Post


**Tags**

id tag_name
1  Published
2  Favorites
3  Deleted


**PostTagRelatives** 

id post_id tag_id
1    1       1
2    1       2
3    2       3

我使用查询

SELECT p.*, GROUP_CONCAT(PostTagRel.tag_id) AS tags FROM Posts p left
join PostTagRelatives PostTagRel on PostTagRel.post_id = p.id GROUP BY
p.id

而且效果很好。

我需要添加到 sql 查询以仅获取包含“已发布”和“收藏夹”标签的帖子。我尝试在 GROUP BY 之前插入一些条件,例如

WHERE (',' || tags || ',') LIKE '%,1,2,%'

但它没有帮助。

【问题讨论】:

    标签: sqlite select join where


    【解决方案1】:

    您可以尝试使用子选择来查找两者。我假设一个 PK 并且一个帖子不能有多次相同的标签。

    SELECT p.*, GROUP_CONCAT(PostTagRel.tag_id) AS tags 
    FROM Posts p 
    left join PostTagRelatives PostTagRel on PostTagRel.post_id = p.id 
    WHERE 2 = ( SELECT COUNT(*)
                FROM PostTagRelatives PTR
                INNER JOIN Tags T ON (T.tag_id = PTR.tag_id AND PTR.post_id = p.post_id )
                WHERE T.tag_name IN ('Published','Favorites') )
    GROUP BY p.id
    

    【讨论】:

    • 另外,很抱歉我在这台笔记本电脑上没有 sqlite3,但我可以稍后测试和调整 SQL,或者如果我遗漏了一些小东西,可以随时编辑它。
    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多