MySQL 按用户分隔值

MySQL separate values by user

我已经从 cmsms 网站恢复了一个数据库,并且 Mysql 我想提取前端用户的所有登录信息。我使用 Heidisql

我的问题user_proprerties数据库是这样的形式:

Id UserID Type    Data
1       2 email   1@2be.net
2       2 company lorme ipsum
3       2 fname   testname
4       5 email&  2@2be.com
5       5 company empty
6       5 fname   dolor sir amed

我希望数据采用这种形式:
Userid email company fname
2 1@2be.be lorem testname
5 2@2be.be emptydolor先生

这是我当前的mysql查询

select 
    cms_module_feusers_users.id,
    cms_module_feusers_users.username,  
    cms_module_feusers_users.createdate,
    cms_module_feusers_users.expires,
    cms_module_feusers_properties.`data` email
from 
    cms_module_feusers_users
    inner join cms_module_feusers_properties on cms_module_feusers_properties.userid = cms_module_feusers_users.id
where
    cms_module_feusers_properties.title = 'email'

但是现在当我想要公司名称和 fname 时我被卡住了。

为您需要的每个字段添加一个联接

SELECT 
    user.id,
    user.whatever,
    <other stuff from cms_module_feusers_users...>
    user_email.`data` as email,
    user_company.`data` as company,
    <other stuff from cms_module_feusers_properties...>
FROM cms_module_feusers_users user
LEFT JOIN cms_module_feusers_properties user_email ON user_email.userid = user.id AND user_email.title = 'email'
LEFT JOIN cms_module_feusers_properties user_company ON user_company.userid = user.id AND user_company.title = 'company'
<other joins from cms_module_feusers_properties...>

WHERE <conditions related to users...>

您需要使用 LEFT JOIN,因为 cms_module_feusers_properties 中可能缺少某些属性。

此外,这还假设每个 属性 对每个用户最多出现一次。

试试这个:

SELECT 
    cms_module_feusers_users.id,
    cms_module_feusers_users.username,
    cms_module_feusers_users.createdate,
    cms_module_feusers_users.expires,
    prop_data.data AS email,
    prop_data_company.data AS company,
    prop_data_fname.data AS fname
FROM
    cms_module_feusers_users
        INNER JOIN
    (SELECT 
        *
    FROM
        cms_module_feusers_properties
    WHERE
        type = 'email') prop_data ON prop_data.userid = cms_module_feusers_users.id
        INNER JOIN
    (SELECT 
        *
    FROM
        cms_module_feusers_properties
    WHERE
        type = 'company') prop_data_company ON prop_data_company.userid = cms_module_feusers_users.id
        INNER JOIN
    (SELECT 
        *
    FROM
        cms_module_feusers_properties
    WHERE
        type = 'fname') prop_data_fname ON prop_data_fname.userid = cms_module_feusers_users.id

(略微)较慢,但更干净...

SELECT p.userid
     , MAX(CASE WHEN type = 'email' THEN data END) email
     , MAX(CASE WHEN type = 'company' THEN data END) company
     , MAX(CASE WHEN type = 'fname' THEN data END) fname
  FROM cms_module_feusers_properties p
 GROUP
    BY p.userid;