MySQL按其他表的匹配排序查询

时间:2018-06-07 01:28:18

标签: mysql sql

我有以下表格:

  • 新闻(id,title,...)
  • news_exchange_relations(id,news_id,exchange_id)
  • news_currency_relations(id,news_id,currency_id)
  • news_country_relations(id,news_id,country_id)

我有一个包含三个参数的搜索表单:交换,货币和国家/地区。我的目标是选择一些参数来查找与所选参数最相关的新闻。

实施例: 如果用户指定了X参数,我想显示与至少一个参数匹配的所有新闻,但首先我将显示与X参数匹配的新闻,而不是X-1等。

详细示例:

新闻:

1, title 1
2, title 2
3, title 3

新闻交流关系:

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实现这一目标?

1 个答案:

答案 0 :(得分:0)

你可以从这开始:

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;  

如果有任何澄清,请告诉我。