gpt4 book ai didi

mysql - 如何在 3 个表之间限制标签

转载 作者:可可西里 更新时间:2023-11-01 08:21:03 25 4
gpt4 key购买 nike

我正在开发标签系统,它应该做的是您可以查询和选择标签,例如jqueryjavascript标签,library。它应该只显示与查询相关的脚本,并且只显示具有标签的脚本。这是数据库布局:

脚本表:

+-----------+---------------+
| script_id | name |
+-----------+---------------+
| 1 | jQuery |
| 2 | Sencha Touch |
| 3 | Codeigniter |
| 4 | Google Chrome |
| 5 | memcached |
| 6 | PHP |
| 7 | MooTools |
| 8 | node.js |
| 9 | jQuery Mobile |
+-----------+---------------+

标签表:

+--------+-------------+-------------+
| tag_id | name | url_name |
+--------+-------------+-------------+
| 1 | JavaScript | javascript |
| 2 | Library | library |
| 3 | PHP | php |
| 4 | MySQL | mysql |
| 5 | Cache | cache |
| 6 | HTML | html |
| 7 | Open source | open-source |
+--------+-------------+-------------+

标记表:

+-----------+--------+-----------+
| tagged_id | tag_id | script_id |
+-----------+--------+-----------+
| 1 | 1 | 1 | # javascript -- jQuery
| 2 | 2 | 1 | # library -- jQuery
| 3 | 1 | 9 | # javascript -- jQuery mobile
+-----------+--------+-----------+

当我运行我的 SQL 时,它仍然选择 jQuery Mobile 但它不应该,因为它不包含 library 标记,其中 jQuery 确实如此,我需要它来限制必须满足所选标签的结果。

这是我的 SQL:

SELECT scripts.script_id,
scripts.name
FROM
(
scripts scripts

LEFT OUTER JOIN tagged tagged ON tagged.script_id = scripts.script_id

LEFT OUTER JOIN tags tags ON tags.tag_id = tagged.tag_id
)
WHERE MATCH(scripts.name) AGAINST ('jquery*' IN BOOLEAN MODE) AND ( tags.url_name = 'javascript' OR tags.url_name = 'library' )
GROUP BY script_id
ORDER BY scripts.name
LIMIT 0, 25

它返回:

+-----------+---------------+
| script_id | name |
+-----------+---------------+
| 1 | jQuery |
| 9 | jQuery Mobile |
+-----------+---------------+

如果我将 OR 更改为 AND,它根本不会返回任何内容,或者如果我从标签 (),它也不会返回任何东西。

如何使查询约束标签?

最佳答案

试一试:

select s.script_id, s.name from scripts s
join tagged tj on s.script_id = tj.script_id
join tags t on t.tag_id = tj.tag_id
where s.name like 'jQuery%' and t.url_name in ('javascript', 'library')
group by s.script_id, s.name
having count(*) = 2
order by s.name
limit 25

唯一需要考虑的是 2 必须替换为 in 子句中的元素数量。

这是 fiddle .

关于mysql - 如何在 3 个表之间限制标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10234345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com