返回与MySQL中列表的2项匹配的记录

时间:2014-02-04 02:25:32

标签: mysql

我有2个表:linkslinks_keywordslinks列有id列,links_keywords列有link_id列和keyword_id列。给定links.id,我希望获得至少有2个匹配关键字的所有links.id作为给定的links.id

例如,要获得只有1个匹配关键字的links.id,我可以这样做:

SELECT links.id 
FROM links 
INNER JOIN keywords ON keywords.link_id=links.id 
LEFT JOIN links links2 on links2.id=keywords.link_id 
WHERE links2.id=1

1 个答案:

答案 0 :(得分:3)

只需加入两个表,按ID分组并应用“至少2个匹配”条件:

SELECT links.id
FROM links
JOIN keywords ON keywords.link_id = links.id
GROUP BY links.id
HAVING COUNT(*) >= 2;

或者,如果您已经在使用外键约束:

SELECT link_id AS id
FROM keywords
GROUP BY link_id
HAVING COUNT(*) >= 2;