2

Here is my table:

 id | title    | lang
----+----------+------
 1  | Moscow   | en
 1  | Москва   | ru
 2  | Helsinki | en 
 2  | Хельсинки| ru

I would like to efficiently get the ru title by en title.

At the moment, I get the id of the entry first and then make another query by hand.

Any other, more elegant, solutions?

3 Answers3

4

A SELF JOIN might be of help and is usually a preferable solution to lots of nested queries, if not for performance reasons (see: Join vs. sub-query, Rewriting Subqueries as Joins) certainly for readability.

In your case try:

SELECT movies_ru.title 
 FROM movies AS movies_ru 
 JOIN movies AS movies_en 
 ON movies_ru.id = movies_en.id
 WHERE movies_ru.lang = "ru"
 AND movies_en.lang = "en"
 AND movies_en.title = "The English Title"
Community
  • 1
  • 1
Tobia Tesan
  • 1,938
  • 17
  • 29
  • 2
    After reading "Join vs sub-query" I have to agree... @DainiusVaičiulis , are you hearing us? – Siguza Jul 27 '15 at 11:03
  • @Siguza *nota bene*: I seem to understand that this is not an universal rule; according to benchmarks found on some Internet outlets, under Oracle, for example, there *seems* to be little or no penalty for nested `SELECT`s over self `JOIN`s. However, I think it's safe to take the MySQL reference manual at face value when it says *"A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better"* – Tobia Tesan Jul 27 '15 at 11:22
1

Edit: It turns out Tobia Tesan's answer is usually better practice.


Use a subselect:

SELECT `title` FROM `table` WHERE `lang` = 'ru' AND `id` = (SELECT `id` FROM `table` WHERE `lang` = 'en' AND `title` = 'Moscow')
Siguza
  • 21,155
  • 6
  • 52
  • 89
-1

you can do this whit this simple query:-

SELECT title FROM table 
WHERE lang = 'ru'
 AND
 id = (SELECT id FROM table WHERE lang = 'en' AND title = 'Moscow')
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
david sam
  • 521
  • 1
  • 8
  • 25