使用MySQL多对多个select语句来查找相对行

时间:2014-09-28 23:16:29

标签: mysql many-to-many inner-join

我尝试使用内部联接来查找相对行。

但似乎它什么都没有回来。请指教。

基本上,我已经从原始页面标题和每篇文章的描述中分解了所有关键字。所以,当我来搜索时,我可以查询关键字表。

这是一篇包含关键字的文章

- 表格架构

CREATE TABLE article         ( id INT, title TEXT, description TEXT );
CREATE TABLE keyword         ( id INT, keyword VARCHAR(255) );
CREATE TABLE article_keyword ( article_id INT, keyword_id INT );

- 添加第1条

insert into article set
id = 1,
title = "my text book like a black hole",
description = "I have a text book. Any people who read it and after days they will disappear. etc...";

- 为第1条添加关键字

insert into keyword set
id = 1,
keyword = "text book";

insert into keyword set
id = 2,
keyword = "black hole";

insert into article_keyword set
article_id = 1,
keyword_id = 1;

insert into article_keyword set
article_id = 1,
keyword_id = 2;

- 添加第2条

insert into article set
id = 2,
title = "the fact of deep space black hole",
description = "More researches are telling fake story about black holes is exists. But my alien friend tell me it is wrong ... etc";

- 为第2条添加关键字

insert into keyword set
id = 3,
keyword = "research";

insert into keyword set
id = 4,
keyword = "alien";

insert into article_keyword set
article_id = 2,
keyword_id = 2;

insert into article_keyword set
article_id = 2,
keyword_id = 3;

insert into article_keyword set
article_id = 2,
keyword_id = 4;

- 使用"教科书",预期1篇文章

SELECT article.id, title FROM article
JOIN article_keyword ak ON ak.article_id = article.id
JOIN keyword k1         ON ak.keyword_id = k1.id
WHERE k1.keyword = "text book"

- 使用"黑洞",预期2篇文章

SELECT article.id, title FROM article
JOIN article_keyword ak ON ak.article_id = article.id
JOIN keyword k2         ON ak.keyword_id = k2.id
WHERE k2.keyword = "black hole"

- 当搜索图书包含所有这些关键字时,则不会获得任何关键字。

SELECT article.id, title FROM article
JOIN article_keyword ak ON ak.article_id = article.id
JOIN keyword k1         ON ak.keyword_id = k1.id
JOIN keyword k2         ON ak.keyword_id = k2.id
WHERE k1.keyword = "text book"
AND   k2.keyword = "black hole";

任何想法mysql都无法回复第1条?

此查询有什么问题吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

是的,您的查询错误,因为第一个where子句将article_keyword和关键字(k1)之间的连接限制为具有keyword = 1和article_id = 1的行,并且没有行将匹配关键字2的第二个where子句。

如果您想要包含多个关键字的文章,可以使用此查询:

SELECT article.id, title 
FROM article
JOIN article_keyword ak ON ak.article_id = article.id
JOIN keyword k          ON ak.keyword_id = k.id
WHERE k.keyword = "text book"
OR    k.keyword = "black hole"
GROUP BY article.id, title
HAVING COUNT(keyword) = 2

答案 1 :(得分:-1)

您的前2个SELECT声明工作正常。在上一个SELECT语句中使用DISTINCTWHERE子句尝试OR而不是AND

SELECT DISTINCT article.id, title FROM article
JOIN article_keyword ak ON ak.article_id = article.id
JOIN keyword k1         ON ak.keyword_id = k1.id
JOIN keyword k2         ON ak.keyword_id = k2.id
WHERE k1.keyword = "text book"
OR   k2.keyword = "black hole";