我面临以下情况。
我们有一个带有翻译实体的 CMS。这些翻译存储在具有一对多关系的不同表中。例如 newsarticles
和 newsarticle_translations
。可用语言
的数量由同一 CMS 动态确定。
当输入一篇新的新闻文章时,编辑需要输入至少一种翻译,他可以选择哪一种可用语言由他决定。
在我们 CMS 的新闻文章概述中,我们想显示一个带有(翻译的)文章标题的专栏,但由于没有一种语言是强制性的(其中一种是强制性的,但我不知道是哪种语言)我不知道我真的知道如何构建我的 mysql 查询来为每篇新闻文章选择一个标题,而不考虑输入的语言。
为了让这一切变得更加困难,我们的经理要求也能够对标题进行排序,因此据我所知,排除了在单独的查询中获取翻译的可能性。
有人知道如何以最有效的方式解决这个问题吗?
这是我的表模式,它可能有帮助
> desc news;
+-----------------+----------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+----------------+------+-----+-------------------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| category_id | int(1) | YES | | NULL | |
| created | timestamp | NO | | CURRENT_TIMESTAMP | |
| user_id | int(10) | YES | | NULL | |
+-----------------+----------------+------+-----+-------------------+----------------+
> desc news_translations;
+-----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| enabled | tinyint(1) | NO | | 0 | |
| news_id | int(1) unsigned | NO | | NULL | |
| title | varchar(255) | NO | | | |
| summary | text | YES | | NULL | |
| body | text | NO | | NULL | |
| language | varchar(2) | NO | | NULL | |
+-----------------+------------------+------+-----+---------+----------------+
PS:我已经考虑过子查询和 coalesce() 解决方案,但那些看起来相当肮脏的技巧,想知道是否有更好的东西知道我没有想到?
最佳答案
这不是一个快速的方法,但我认为它可以满足您的需求。
让我知道它是如何工作的,我们接下来可以提高速度:)
select nt.title
from news n
join news_translations nt on(n.id = nt.news_id)
where nt.title is not null
and nt.language = (
select max(x.language)
from news_translations x
where x.title is not null
and x.new_id = nt.news_id)
order
by nt.title;
关于php - MySQL数据库的复杂排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067487/