there was an idea to replace two requests to the database with one, is it possible to do this?

SELECT `label` AS `from` FROM `city` WHERE `code` = 'moscow' SELECT `label` AS `to` FROM `city` WHERE `code` = 'irkutsk' 

The result to be obtained in one request should be:

enter image description here

  • Need to get two rows or two columns in one row? - Dmitry Kozlov
  • two columns with different rows - user193361

3 answers 3

Not quite clear the database that you have. When combined, you may get an undesirable result, so requests may not be entirely correct.

Alternatively, you can combine 2 queries via UNION (1 column, rows under each other):

 SELECT `label` AS `from` FROM `city` WHERE `code` = 'moscow' UNION SELECT `label` AS `to` FROM `city` WHERE `code` = 'irkutsk' 

You can make it so that there are 2 columns label - to and from :

 SELECT * FROM (SELECT `label` AS `from` FROM `city` WHERE `code` = 'moscow') c1, (SELECT `label` AS `to` FROM `city` WHERE `code` = 'irkutsk') c2 

    In case you are satisfied with two returned rows, in the first column of which the city will be indicated, you can proceed as follows

     SELECT `code`, `label` FROM `city` WHERE `code` IN('moscow', 'irkutsk') 

    If the line should be one, you can proceed as follows

     SELECT from.label AS from, to.table AS to FROM (SELECT `label` FROM `city` WHERE `code` = 'moscow' LIMIT 1) AS from LEFT JOIN (SELECT `label` FROM `city` WHERE `code` = 'irkutsk' LIMIT 1) AS to 
    • You may get an undesirable result (extra lines) - you can get a label, where from = moscow - Denis
    • @Denis You are right, cited an alternative. - cheops

    From the request:

     SELECT `code`, `label` FROM `city` WHERE `code` IN('moscow', 'irkutsk') 

    In other DBMSs, you can get one line with a simple PIVOT .

    But you have MySQL , so you can do this:

     SELECT MAX(IF(`code`='moscow',`label`,null)) as `from`, MAX(IF(`code`='irkutsk',`label`,null)) as `to` FROM `city` WHERE `code` IN('moscow', 'irkutsk')