Home  >  Q&A  >  body text

MySQL: "Select text from... as <variable here or subquery>"

I have the following table which contains the following data:

id text language
1 German text German
2 English text English

What I want is to get results in the following format:

german="deutscher text"
english="english text"

means not :

text="deutscher text"
text="english text"

Key/column nametext should be data from language

I tried the following query but it doesn't work:

SELECT text as (SELECT language FROM `table` where id = 1) FROM `table` where id = 1;

(SELECT language FROM table where id = 1) will return "german", so the query should be: "Select german text from table where id = 1;" but this doesn't work.

Is there a way to do this in one query?

Cheers, Thomas

P粉012875927P粉012875927194 days ago686

reply all(2)I'll reply

  • P粉805931281

    P粉8059312812024-04-07 16:18:50

    You have to change the table schema slightly; added a reference to group by languages ​​you want to use

    CREATE TABLE IF NOT EXISTS `test` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `ref` int(11) DEFAULT 0,
      `text` varchar(50) DEFAULT NULL,
      `language` varchar(50) DEFAULT NULL,
      KEY `Index 1` (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;

    Then SQL

    SELECT T.text AS english, T2.text AS german
    FROM test T 
    INNER JOIN test T2 ON T.ref = T2.ref AND T2.`language` = 'german'
    WHERE 
        T.ref = 1 AND
        T.language = 'english'
    

    Virtual data

    INSERT INTO `test` (`id`, `ref`, `text`, `language`) VALUES
        (1, 1, 'deutscher text', 'german'),
        (2, 1, 'english text', 'english');
    

    reply
    0
  • P粉520545753

    P粉5205457532024-04-07 13:43:46

    One option you can use is PREPARED STATMENT:

    SET @sql := NULL;
    
    SELECT GROUP_CONCAT(
               CONCAT('MAX(CASE WHEN language="',language,'" THEN text END) AS "',language,'"')) 
             INTO @sql
    FROM mytable;
    
    SELECT CONCAT('SELECT ',@sql,' FROM mytable;') INTO @sql;
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    The first step is to dynamically allocate the columns required by the @sql variable. The previously assigned @sql variable is then concatenated with the rest of the final SELECT query and reassigned to the @sql variable. The query will be as follows:

    SELECT MAX(CASE WHEN language="german" THEN text END) AS "german",
           MAX(CASE WHEN language="english" THEN text END) AS "english" 
    FROM mytable;

    Finally, we prepare, execute and then deallocate the statement allocated in the @sql variable and you will get the expected results.

    Demo Violin

    reply
    0
  • Cancelreply