将值转换为SQL列

时间:2018-05-05 15:59:56

标签: mysql sql

我正在使用以下SQL查询:

SELECT package_stats.developer, xf_user.username, xf_user.email, xf_user_profile.homepage, xf_user_profile.location, xf_user_profile.about, xf_user_field_value.field_id, xf_user_field_value.field_value 
FROM package_stats, xf_user, xf_user_field_value, xf_user_profile 
WHERE xf_user.username = package_stats.developer AND xf_user_field_value.user_id = xf_user.user_id AND xf_user_profile.user_id = xf_user.user_id

这就是这样的:

enter image description here

我的问题是,使用SQL查询是否可以将不同的field_id值放入列中,以便我只有一行。

2 个答案:

答案 0 :(得分:1)

您可以使用CASE

SELECT 
    CASE WHEN xf_user_field_value.field_id = 'Github' THEN xf_user_field_value.field_id ELSE '' end) as 'Col Header Github',
    CASE WHEN xf_user_field_value.field_id = 'Repository' THEN xf_user_field_value.field_id ELSE '' end) as 'Col Header Repository',
    CASE WHEN xf_user_field_value.field_id = 'UserRole' THEN xf_user_field_value.field_id ELSE '' end) as 'Col Header UserRole',
    CASE WHEN xf_user_field_value.field_id = 'aim' THEN xf_user_field_value.field_id ELSE '' end) as 'Col Header aim',
    CASE WHEN xf_user_field_value.field_id = 'twitter' THEN xf_user_field_value.field_id ELSE '' end) as 'Col Header twitter', 
/*other_col_name...*/

答案 1 :(得分:0)

如果您需要在同一行上显示结果,则每次需要谷值时都应加入xf_user_field_value,例如:

SELECT package_stats.developer
      , xf_user.username
      , xf_user.email
      , xf_user_profile.homepage
      , xf_user_profile.location
      , xf_user_profile.about
      , v1.field_value as Github
      , v2.field_value as Repository
      , v3.field_value as UserRole
      , v4.field_value as aim
      , v5.field_value as twitter 

FROM package_stats
INNER JOIN  xf_user ON xf_user.username = package_stats.developer
INNER JOIN xf_user_profile  ON xf_user_profile.user_id = xf_user.user_id 
INNER JOIN  xf_user_field_value v1 ON v1.user_id = xf_user.user_id and 'v1.field_id' = 'Github'
INNER JOIN  xf_user_field_value v2 ON v2.user_id = xf_user.user_id and 'v2.field_id' = 'Repository'
INNER JOIN  xf_user_field_value v3 ON v3.user_id = xf_user.user_id and 'v3.field_id' = 'UserRole'
INNER JOIN  xf_user_field_value v4 ON v4.user_id = xf_user.user_id and 'v4.field_id' = 'aim'
INNER JOIN  xf_user_field_value v5 ON v5.user_id = xf_user.user_id and 'v5.field_id' = 'twitter'