2011-08-18 175 views
1

這是有點艱難,我猜。mysql concat子查詢結果作爲一個子查詢本身

我想要實現的是通過group_concat生成一個字符串,然後將其作爲查詢運行。我的查詢返回 numCustomers作爲查詢我想運行。

是否有可能在主查詢中將其作爲查詢運行?

我的查詢如下:

SELECT 
lastSent,tblmailinglistgroups.addDate,title, tblmailinglistgroups.active, tblmailinglistgroups.id,groupType, 
CASE 
WHEN (groupType='s') THEN (SELECT COUNT(id) FROM tblmailinglistgroupscusts WHERE groupID=tblmailinglistgroups.id) 
WHEN (groupType='d') THEN (
CONCAT('SELECT COUNT(tblcustomers.id) FROM tblcustomers INNER JOIN tblcustomersextension ON tblcustomers.id=tblcustomersextension.customerID WHERE 1=1 ', 
(SELECT GROUP_CONCAT(filterAndOr,' ',openBrackets,' ',filterBy, ' ',(
SELECT 
CASE 
WHEN filterOperator='ne' THEN '!=' WHEN filterOperator='e' THEN '=' WHEN filterOperator='be' THEN '>=' WHEN filterOperator='se' THEN '<=' WHEN filterOperator='b' THEN '>' WHEN filterOperator='s' THEN '<' WHEN filterOperator='in' THEN 'in' WHEN filterOperator='ni' THEN 'not in' WHEN 'nu' THEN 'IS NULL' 
END AS operator),' \'',filterValue,'\' ',closeBrackets SEPARATOR ' ') AS x 
FROM `tblmailinglistgroupsrules1` 
WHERE groupID=tblmailinglistgroups.id 
) 
) 
) END AS numCustomers 
FROM 
tblmailinglistgroups 
LEFT JOIN tblmailinglistgroupscusts ON (tblmailinglistgroupscusts.groupID = tblmailinglistgroups.id) 
GROUP BY tblmailinglistgroups.id 
ORDER BY tblmailinglistgroups.id DESC 

表structes是:

CREATE TABLE IF NOT EXISTS `tblmailinglistgroups` (
`id` bigint(12) NOT NULL AUTO_INCREMENT, 
`title` varchar(100) NOT NULL DEFAULT '', 
`addDate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', 
`active` enum('on','off') NOT NULL DEFAULT 'on', 
`lastSent` date NOT NULL DEFAULT '0000-00-00', 
`groupType` enum('s','d') NOT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=67 ; 


CREATE TABLE IF NOT EXISTS `tblmailinglistgroupscusts` (
`id` bigint(12) NOT NULL AUTO_INCREMENT, 
`groupID` bigint(12) NOT NULL DEFAULT '0', 
`custID` int(5) NOT NULL, 
`email` varchar(200) NOT NULL DEFAULT '', 
`phone` varchar(20) NOT NULL, 
`comments` varchar(250) NOT NULL, 
`addDate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', 
PRIMARY KEY (`id`), 
KEY `groupID` (`groupID`), 
KEY `custID` (`custID`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7813 ; 


CREATE TABLE IF NOT EXISTS `tblmailinglistgroupsrules1` (
`id` int(5) NOT NULL AUTO_INCREMENT, 
`groupID` int(5) NOT NULL, 
`filterAndOr` enum('AND','OR') NOT NULL, 
`openBrackets` enum('','(','((','(((','((((') NOT NULL, 
`filterBy` varchar(40) NOT NULL, 
`filterOperator` varchar(40) NOT NULL, 
`filterValue` varchar(40) NOT NULL, 
`closeBrackets` enum('',')','))',')))','))))') NOT NULL, 
`showOrder` int(5) NOT NULL, 
`addDate` datetime NOT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=415 ; 

回答

0

你可以使用存儲過程從CONCAT執行查詢。在簡單的SQL查詢中沒有辦法做到這一點。

一個很好的解釋可以在這裏找到:http://www.it-iss.com/mysql/mysql-stored-procedures-and-dynamic-sql/

危險:如果這是一個Web應用程序,有可能爲攻擊者manipuate的CONCAT語句的結果來執行自己的,壞之類的語句DROP DATABASE