sql >> Database teknologi >  >> RDS >> Mysql

MySQL-forespørgsel INNER JOIN med aliaser

I dette tilfælde kan du gøre det sådan her;) Bare en simpel tabelpivot.

select
    users.id,
    users.slug,
    users.name,
    max(if(users_info.info_key = 'email', users_info.info_val, null)) as email,
    max(if(users_info.info_key = 'age', users_info.info_val, null)) as age
from users
inner join users_info
on users.id = users_info.parent
group by users.id

SQLFiddle DEMO HER

Hvis du har en dynamisk info_key , skal du bruge en dynamisk sql for at gøre dette, her giver jeg dig et eksempel.

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(if(users_info.info_key = ''',
      users_info.info_key,
      ''', users_info.info_val, null)) as ',
      users_info.info_key
    )
  ) INTO @sql
FROM users
inner join users_info
on users.id = users_info.parent
;

SET @sql = CONCAT('select users.id, users.slug, users.name, ', @sql, ' FROM users
inner join users_info group by users.id having email = \'[email protected]\'');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLFiddle DEMO HER



  1. Undgå linjeskift i MySQL-output

  2. Sådan fungerer Cot() i PostgreSQL

  3. Opret en midlertidig tabel i SQLite

  4. Sådan summerer du en enkelt kolonne baseret på gruppering i MySQL