简体   繁体   English

MySQL - 关系数据库和标记

[英]MySQL - Relational Databases and Tagging

I have been scratching my head on this one for a while, so I figured I'd ask stack overflow (Note: I am an SQL novice trying to learn more SQL, so please be respectful and explanatory):我一直在摸索这个问题,所以我想我会问堆栈溢出(注意:我是 SQL 新手,试图了解更多 SQL,所以请尊重和解释):

I have one sql table that looks like this called "posts":我有一张 sql 表,看起来像这样,称为“帖子”:

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

And another called "tags" that stores the tags on the posts (in the "posts" table) in text:另一个称为“标签”的标签以文本形式存储在帖子(在“帖子”表中)上:

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

(To clarify, the concept where: id=0 is tagged php,mysql; id=1 is tagged sql,mysql; id=2 is tagged php; id=3 is tagged perl.) (To clarify, the concept where: id=0 is tagged php,mysql; id=1 is tagged sql,mysql; id=2 is tagged php; id=3 is tagged perl.)

How could I write a WHERE statement to get posts tagged x, but not y (x and y will be defined by php)?我如何编写 WHERE 语句来获取标记为 x 而不是 y 的帖子(x 和 y 将由 php 定义)?

For example, how could I get all posts tagged mysql but not php?例如,我怎样才能获得所有标记为 mysql 而不是 php 的帖子?

EDIT编辑

Could you also explain how to add multiple tags to search for (for example get all tagged mysql and recursion but not php)您能否解释一下如何添加多个标签进行搜索(例如获取所有标记的 mysql 和递归但不是 php)

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

example 2: get all tagged mysql and recursion but not php:示例 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

My suggestion with EXISTS:我对 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')

Naively, simply and portably:天真、简单、便携:

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

Now depending upon the execution plan, you can do other things to optimize this.现在根据执行计划,您可以做其他事情来优化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM