MySQL根据其他表中的匹配项对查询进行排序
我有以下表格:MySQL根据其他表中的匹配项对查询进行排序,mysql,sql,Mysql,Sql,我有以下表格: 新闻(id、标题等) 新闻交换关系(id、新闻id、交换id) 新闻与货币关系(id、新闻与id、货币与id) 新闻与国家关系(id、新闻与国家id) 我有一个带有三个参数的搜索表单:汇率、货币和国家。我的目标是通过选择一些参数来查找与所选参数最相关的新闻 例如: 如果用户指定了X个参数,我希望显示至少与其中一个参数匹配的所有新闻,但首先我将显示与X个参数匹配的新闻,而不是与X-1匹配的新闻,依此类推 详细示例: 新闻: 新闻交流关系: 1, 1, 1 2, 2, 1 1,
- 新闻(id、标题等)
- 新闻交换关系(id、新闻id、交换id)
- 新闻与货币关系(id、新闻与id、货币与id)
- 新闻与国家关系(id、新闻与国家id)
1, 1, 1
2, 2, 1
1, 1, 1
2, 2, 1
1, 1, 1
2, 2, 2
新闻与国家关系:
1, 1, 1
2, 2, 1
1, 1, 1
2, 2, 1
1, 1, 1
2, 2, 2
新闻货币关系:
1, 1, 1
2, 2, 1
1, 1, 1
2, 2, 1
1, 1, 1
2, 2, 2
搜索参数:
Country =1, exchange = 1, currency = 1
结果:
Id | title | matches
1, title1, 3
2, title2, 2
只有MySQL才能实现这一点吗?您可以从以下内容开始:
create table want as
select a.*,
(case when b.id is null then 0 else 1 end) + (case when c.id is null then 0 else 1 end) + (case when d.id is null then 0 else 1 end) as matches
from
news a
left join
(select * from news_exchange_relations
where exchange_id = 1) b
on a.id = b.id
left join
(select * from news_currency_relations
where currency_id = 1) c
on a.id = c.id
left join
(select * from news_country_relations
where country_id = 1) d
on a.id = d.id
having matches > 0;
如有任何澄清,请务必告诉我。样本数据和预期结果将非常有用。谢谢您的回复。我已经编辑了我的帖子(乐意帮忙:)