0

我有 3 个表:链接、关键字和关键字链接。一个链接可以有多个关键字,多个链接可以有相同的关键字。keywords_links用于连接linkskeywords。当我运行以下查询时,由于多个关键字匹配,因此返回了同一链接的多行。如何修改此查询以返回唯一行?

SELECT links . * 
FROM  `links` 
INNER JOIN keywords_links ON keywords_links.link_id = id
INNER JOIN keywords ON keywords.id = keywords_links.keyword_id
WHERE keywords.keyword
IN (
'php', 'sql', 'html', 'css'
)
4

1 回答 1

1

最简单的方法是DISTINCTSELECT:

SELECT DISTINCT links.*
...
...

但也许更有效的解决方案是重写您的查询,以便不必在每一列之间进行区分:

SELECT a.*
FROM links a
INNER JOIN
(
    SELECT a.link_id
    FROM keywords_links a
    INNER JOIN keywords b ON
        a.keyword_id = b.id AND
        b.keyword IN ('php', 'sql', 'html', 'css')
    GROUP BY a.link_id
) b ON a.id = b.link_id
于 2012-07-12T01:32:10.413 回答