0

i need some query.

CREATE TABLE `location_areas_localized` (
  `id` int(11) DEFAULT NULL,
  `lang_index` varchar(5) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  KEY `id` (`id`),
  KEY `lang_index` (`lang_index`),
  KEY `name` (`name`),
  FULLTEXT KEY `name_2` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


INSERT INTO `location_areas_localized` (`id`, `lang_index`,`name`)
VALUES
    (1,'ru','Нью Йорк'),
    (1,'en','New York'),
    (2,'en','Boston'),
    (2,'ch','波士顿')
;

Logic of search.

If row with lang_index='ru' AND id IN(1,2) found. it must return all with lang_index='ru' If one or more rows with lang_index='ru' not exists But exists with lang_index='en' and with some id. Then it must return all exists with land_index='ru' AND id IN(1,2) and all that not found with lang_index='ru' but found with lang_index='en' (in table - all rows with lang_index='en' always exists)

See on sqlfiddle

I need only one result per id. I tried GROUP BY id but its not works correctly.

Output must be

  1,'ru','Нью Йорк'

   2,'en','Boston'   (because lang_index='ru' with id 2  not found)
4

2 回答 2

1
SELECT 
  coalesce(max(CASE WHEN lang_index='ru' THEN name ELSE null END), name) as name
FROM 
  location_areas_localized 
WHERE 
  id IN (1,2) 
  AND (lang_index='en' OR lang_index='ru')
group by 
  id
ORDER BY 
  FIELD(lang_index,'ru','en');
于 2013-01-18T09:02:53.810 回答
0

不使用聚合函数,它只需要第一个匹配的行。子查询ORDER BY强制执行相同的事实,即id“ru”(或“en”,如果“ru”不存在)行是第一个。

SELECT * 
FROM(
    SELECT *
    FROM location_areas_localized
    ORDER BY FIELD(lang_index,'ru','en','ch')
) as inv
WHERE id IN (1,2)
GROUP BY id

请参阅SQLFiddle示例

于 2013-01-18T08:57:44.973 回答