给定这些表:
id_article | title
1 | super article
2 | another article
id_tag | title
1 | great
2 | awesome
id_relation | id_article | id_tag
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
Run Code Online (Sandbox Code Playgroud)
我希望能够选择所有“很棒”和“很棒”的文章(最终,我可能也必须实现 OR)
基本上,如果我对文章进行选择,关系表将连接到 id_article:当然,我无法连接两个不同的 id_tag 值。我唯一的线索是连接 ID 以字符串形式进行测试,但这看起来很蹩脚,必须有一个更漂亮的解决方案。
哦,如果重要的话,我使用 MySQL 服务器。
编辑:对于 ByWaleed,我在原来的问题中引用的典型的 sql 选择肯定会失败:
SELECT
a.id_article,
a.title
FROM articles a, relations r
WHERE
r.id_article = a.id_article and r.id_tag = 1 and r.id_tag = 2
Run Code Online (Sandbox Code Playgroud)
不起作用,因为 r.id_tag 显然不能是同一行上的 1 和 2。我怀疑 w3schools 是否有相关文章。我在谷歌上的搜索没有产生任何结果,可能是因为我搜索了错误的关键字。
如果您正常执行所有联接,然后按文章将行聚合到一组,那么您可以断言它们必须至少有两个不同的标签。
(已经过滤到great和/或awesome,这意味着它们两者都有。)
SELECT
a.id_article,
a.title
FROM
articles a
INNER JOIN
relations r
ON r.id_article = a.id_article
INNER JOIN
tags t
ON t.id_tag = r.id_tag
WHERE
t.title IN ('great', 'awesome')
GROUP BY
a.id_article,
a.title
HAVING
COUNT(DISTINCT t.id_tag) = 2
Run Code Online (Sandbox Code Playgroud)
(例如,这DISTINCT是为了避免一篇文章出现两次的可能性。)'great'
为此OR,您只需删除该HAVING子句即可。
| 归档时间: |
|
| 查看次数: |
3123 次 |
| 最近记录: |