我有2个表:links
和links_keywords
。 links
列有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
答案 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;