Mysql
 sql >> Base de données >  >> RDS >> Mysql

Requête MySQL INNER JOIN avec des alias

Dans ce cas, vous pouvez le faire comme ceci ;) Juste un simple pivot de table.

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

DÉMO SQLFiddle ICI

Si vous avez une info_key dynamique , vous aurez besoin d'un sql dynamique pour ce faire, ici je vous donne un exemple.

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;

DÉMO SQLFiddle ICI