将多行合并为一行

时间:2013-02-15 13:28:22

标签: mysql rows

我有以下查询,但这一行返回3行,我想要一行; - )

SELECT 
b_firstname ,value
FROM
cscart_user_profiles
RIGHT JOIN profile_fields_data ON profile_fields_data.object_id =    user_profiles.profile_id
WHERE 
user_profiles.b_title NOT LIKE ''
AND user_profiles.profile_id = '4252'
AND (
    profile_fields_data.field_id ='69' 
    OR 
    profile_fields_data.field_id ='73' 
    OR 
    profile_fields_data.field_id ='75'
)

...但这将返回3行:

user1 value
user1 value
user1 value

我想要一行:

user1 value69 user73 value75

我该如何解决这个问题?

数据为

的2个表格下方
 CREATE TABLE IF NOT EXISTS `cscart_user_profiles` (
  `profile_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `profile_type` char(1) NOT NULL DEFAULT 'P',
  `b_title` varchar(32) NOT NULL DEFAULT '',
  `b_firstname` varchar(128) NOT NULL DEFAULT '',
  `b_lastname` varchar(128) NOT NULL DEFAULT '',
  `b_address` varchar(64) NOT NULL DEFAULT '',
  `b_address_2` varchar(64) NOT NULL DEFAULT '',
  `b_city` varchar(64) NOT NULL DEFAULT '',
  `b_county` varchar(32) NOT NULL DEFAULT '',
  `b_state` varchar(32) NOT NULL DEFAULT '',
   ......
  PRIMARY KEY (`profile_id`),
  KEY `uid_p` (`user_id`,`profile_type`),
  KEY `profile_type` (`profile_type`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;

CREATE TABLE IF NOT EXISTS `cscart_profile_fields_data` (
  `object_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `object_type` char(1) NOT NULL DEFAULT 'U',
  `field_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `value` varchar(255) NOT NULL DEFAULT '0',
  PRIMARY KEY (`object_id`,`object_type`,`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

2 个答案:

答案 0 :(得分:1)

您可以单独加入profile_fields_data表3,以便在一行中获得3个单独的值。

SELECT  b_firstname, 
        pfd69.value as value69, 
        pfd73.value as value73, 
        pfd75.value as value75 

FROM    cscart_user_profiles AS up

        RIGHT JOIN cscart_profile_fields_data AS pfd69
        ON pfd69.object_id = up.profile_id      
        AND pfd69.field_id ='69'

        RIGHT JOIN cscart_profile_fields_data AS pfd73
        ON pfd73.object_id = up.profile_id      
        AND pfd73.field_id ='73'

        RIGHT JOIN cscart_profile_fields_data AS pfd75
        ON pfd75.object_id = up.profile_id      
        AND pfd75.field_id ='75'

WHERE   up.b_title NOT LIKE ''
        AND up.profile_id = '4252'

答案 1 :(得分:0)

您可以使用嵌套查询吗?

SELECT * FROM (
   SELECT User1, Value69 FROM table ) AS T1
INNER JOIN (
   SELECT User2, Value75 FROM table ) AS T2 ON T1.Somevalue = T2.Somevalue

等。

但是没有看到你的架构,就很难写出一个有用的例子