2014-11-03 29 views
0

我想創建以下準備語句,將輸出數據透視表的動態行。如果'名稱'字段沒有空格,我的聲明就可以工作。然而,當我添加空格它(項目實力企業協調,例如),我收到以下錯誤:MySQL準備語句不工作時,字段有空格

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Strength Site Coordinator,MAX(IF(Name = 'TeenEatsSiteCoordinator', Name, NULL)) ' at line 1: PREPARE stmt FROM @sql"

我試圖研究這個問題,並沒有發現任何東西。

這是SQL Fiddle

感謝您的幫助!

CREATE TABLE `Contacts` (
    `Contact_Id` int(11) unsigned NOT NULL, 
    `First_Name` varchar(50) NOT NULL, 
    `Last_Name` varchar(50) NOT NULL 
); 

insert into Contacts values (1, 'John', 'Doe'); 
insert into Contacts values (2, 'Jane', 'Doe'); 

CREATE TABLE `Contact_Types` (
    `Contact_Type_Id` int(11) unsigned NOT NULL, 
    `Name` varchar(50) NOT NULL 
); 

insert into Contact_Types values (1, 'ProjectStrengthSiteCoordinator'); 
insert into Contact_Types values (2, 'TeenEatsSiteCoordinator'); 

CREATE TABLE `Contacts_Contact_Types` (
    `Contact_Id` int(11) unsigned NOT NULL DEFAULT '0', 
    `Contact_Type_Id` int(11) unsigned NOT NULL DEFAULT '0' 
); 

insert into Contacts_Contact_Types values (1, 1); 
insert into Contacts_Contact_Types values (1, 2); 
insert into Contacts_Contact_Types values (2, 1); 

SET @sql = NULL; 

SELECT 
GROUP_CONCAT(DISTINCT 
    CONCAT(
     'MAX(IF(Name = ''', 
     Name, 
     ''', Name, NULL)) AS ', 
     Name 
    ) 
) INTO @sql 
from Contact_Types; 

SET @sql = CONCAT('SELECT c.First_Name, ', @sql, ' from Contacts c 
left join Contacts_Contact_Types cct 
    on c.Contact_Id = cct.Contact_Id 
left join Contact_Types ct 
    on cct.Contact_Type_Id = ct.Contact_Type_Id 
group by c.Contact_Id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 
+0

您需要在反引號中用空格包裝字段名稱。 – 2014-11-03 22:19:14

+0

@RocketHazmat我更新了我的代碼,並在反引號內封裝了Name字段。但是,我仍然收到同樣的錯誤。感謝您及時的回覆。 – 2014-11-03 22:30:06

回答

1

你需要逃避它在as部分:

SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(Name = ''', Name, ''', Name, NULL)) AS `', Name, '`' 
            ) 
        ) INTO @sql 
from Contact_Types; 

請注意,group_concat()需要多個參數,所以嵌套concat()是,嚴格來說,是不必要的。

+0

謝謝!那樣做了。感謝關於'concat()'的反饋。我會擺脫它。美好的一天! – 2014-11-03 22:39:41