mysql concat子查询结果作为子查询本身

时间:2011-08-18 16:15:08

标签: mysql subquery group-concat 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

表格结构是:

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 ;

1 个答案:

答案 0 :(得分:0)

您可以使用存储过程从concat执行查询。在简单的SQL查询中无法做到这一点。

可在此处找到一个很好的解释:http://www.it-iss.com/mysql/mysql-stored-procedures-and-dynamic-sql/

危险:如果这是一个Web应用程序,攻击者可能会操纵concat语句的结果来执行自己的错误语句,如DROP DATABASE