簡體   English   中英

MySQL - 關系數據庫和標記

[英]MySQL - Relational Databases and Tagging

我一直在摸索這個問題,所以我想我會問堆棧溢出(注意:我是 SQL 新手,試圖了解更多 SQL,所以請尊重和解釋):

我有一張 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

(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.)

我如何編寫 WHERE 語句來獲取標記為 x 而不是 y 的帖子(x 和 y 將由 php 定義)?

例如,我怎樣才能獲得所有標記為 mysql 而不是 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

示例 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

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

天真、簡單、便攜:

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

現在根據執行計划,您可以做其他事情來優化它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM