2013-02-15 154 views
1

我有以下查詢,但是這一次返回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 

我想1行:

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; 
+1

考慮發佈您的數據庫架構和示例數據。 – Minesh 2013-02-15 13:30:08

+0

@minesh,你呢? – Bas 2013-02-15 14:11:37

回答

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' 
+0

一個正確的連接工作正常,但不是3個。我得到這個錯誤:#1066 - 不是唯一的表/別名:'cscart_profile_fields_data' – Bas 2013-02-15 13:56:58

+0

現在再試一次。在您原來的SQL中,您加入了profile_fields_data表,而不是cscart_profile_fields_data。我更新了我的SQL。我還用我的where子句修復了一個別名問題。 – Tom 2013-02-15 14:56:59

+0

它的作品!謝謝!!!我不能投票需要聲望;-)但是,謝謝! – Bas 2013-02-15 15:05:17

0

你可以使用嵌套查詢?

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

但沒有看到您的架構很難寫一個有用的例子

+0

你需要我什麼? – Bas 2013-02-15 14:02:08