MySQL外键选择匹配

时间:2016-12-25 19:05:12

标签: mysql

我有一个包含文章的数据库。所有文章都有关键字。关键字位于单独的表中,关键字和文章与关系表相关联,因此:

制品

CREATE TABLE `articles` (
  `id` int(11) NOT NULL,
  `articleTitle` varchar(50) NOT NULL,
  `articleBody` text NOT NULL,
  `articlePermalink` varchar(50) NOT NULL,
  `articleAuthor` int(11) NOT NULL,
  `createdAt` datetime DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

关键字

CREATE TABLE `keywords` (
  `id` int(11) NOT NULL,
  `keyword` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

articlekeywords

CREATE TABLE `articlekeywords` (
  `id` int(11) NOT NULL,
  `articleId` int(11) NOT NULL,
  `keywordId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我想选择所有与使用articles.id作为标识符的任何给定文章中的部分或全部关键字相关的文章。最好只使用一次SQL调用。

修改

我最终做的事与Gordon Linoff suggested below非常相似。

SELECT DISTINCT a.articleTitle, a.articlePermalink
FROM articles a
JOIN articlekeywords ak ON a.id = ak.articleId
JOIN articlekeywords ak2 ON ak.keywordId = ak2.keywordId AND ak2.articleId = $articleId AND not(a.id = $articleId)

2 个答案:

答案 0 :(得分:1)

这是一个自我加入。您可以通过以下方式获得按共同关键字数量排序的匹配文章:

select ak2.article2, count(*) as numKeywordsInCommon
from articlekeywords ak join
     articlekeywords ak2
     on ak.keywordid = ak2.keywordid and ak2.articleid = $arcticleid
group by ak2.articleid
order by numKeywordsInCommon desc;

答案 1 :(得分:1)

这将为您提供由articlekeywords表中的关系标识的完整列表:

SELECT * FROM articlekeywords AKW
JOIN articles A ON AKW.articleId = A.Id
JOIN keywords K ON AKW.keywordId = K.Id
-- WHERE (some condition you'd like to do for further filtering)