mysql - MySQL sort query by matches from other tables
问题描述
I have the following tables:
- news (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)
I have a search form with three parameters: exchange, currency and country. My goal is by selecting some of the parameters to find those news which are most relevant to the selected parameters.
Example: If the user has specified X parameters I want to show all news which match at least one of the parameters, but first I will display news matching X parameters, than X-1 and so on.
Detailed example:
News:
1, title 1
2, title 2
3, title 3
News exchange relations:
1, 1, 1
2, 2, 1
News country relations:
1, 1, 1
2, 2, 1
News currency relations:
1, 1, 1
2, 2, 2
Search parameters:
Country =1, exchange = 1, currency = 1
Results:
Id | title | matches
1, title1, 3
2, title2, 2
Is it possible that to achieve that only with MySQL ?
解决方案
You can start with this:
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;
Do let me know in case of any clarifications.
推荐阅读
- java - 在android studio中获取带有JSON的数组列表
- r - 我想替换 R 中数据集中年份列的“NA”值
- ios - 在 swift4 中未调用 DatabaseReference.observe
- c# - 异步调用适用于控制台但不适用于 webapi
- python - 即使使用 requests.history 从重定向 2 次的 url 下载 pdf 文件也会失败
- javascript - ES6 async/await 在 Observables 和流失败时如何工作?
- c++ - glTextImage2D 没有返回所需的输出(OpenGL)
- database-design - 为什么非依赖保持 BCNF 分解仍然被认为是在 BCNF 中?
- java - 如何将秒变为小时,小时值不能超过 24 小时。?
- delphi - 如何处理 Synedit 表名上的链接?