MySQL - 关系数据库和标记

时间:2011-08-13 02:16:27

标签: mysql sql

我一直在讨论这个问题,所以我想我会问堆栈溢出(注意:我是一个SQL新手试图学习更多的SQL,所以请尊重和解释):

我有一个看起来像这个名为“posts”的sql表:

id | user
--------------------------------
0  | tim
1  | tim
2  | bob

另一个名为“标签”的标签将标签存储在文章的帖子中(在“帖子”表中):

id | postID | tag
--------------------------------
0  | 0      | php
1  | 2      | php
2  | 0      | mysql
3  | 1      | mysql
4  | 1      | sql
5  | 3      | perl

(澄清一下,概念:id = 0标记为php,mysql; id = 1标记为sql,mysql; id = 2标记为php; id = 3标记为perl。)

我怎么能写一个WHERE语句来获取标记为x的帖子,但不能写y(x和y将由php定义)?

例如,我如何才能将所有帖子标记为mysql而不是php?

修改

你能否解释如何添加多个标签进行搜索(例如获取所有标记的mysql和递归但不是php)

3 个答案:

答案 0 :(得分:2)

select *
from
    (select distinct postID
    from tags
    where tag = "mysql") as t1
left join
    (select distinct postID
     from tags
     where tag = "php") as t2
using (postID)
where t2.postID is NULL

示例2:获取所有标记的mysql和递归但不是php:

select *
from
    ((select distinct postID
    from tags
    where tag = "mysql") as t1
join
    (select distinct postID
    from tags
    where tag = "recursion") as t3
using (postID))
left join
    (select distinct postID
     from tags
     where tag = "php") as t2
using (postID)
where t2.postID is NULL

答案 1 :(得分:1)

我对EXISTS的建议:

SELECT DISTINCT postID
FROM tags t1
WHERE EXISTS(SELECT NULL
             FROM tag t2
             WHERE t2.id = t1.id
               AND t2.tag = 'x')
  AND NOT EXISTS(SELECT NULL
                   FROM tag t2
                  WHERE t2.id = t1.id
                    AND t2.tag = 'y')

答案 2 :(得分:1)

天真,简单而便携:

SELECT *
FROM posts
WHERE EXISTS (SELECT * FROM tags WHERE tags.postid = posts.id AND tags.tag = 'x')
AND NOT EXISTS (SELECT * FROM tags WHERE tags.postid = posts.id AND tags.tag = 'y')

现在,根据执行计划,您可以做其他事情来优化它。