我有这个问题,http://sqlfiddle.com/#!9/1a579/3
我使用动态查询构建了它。需要知道如何从中过滤记录。我需要将此查询的结果视为一个表。让我们说CustomUser表。所以我需要查询这个表,如下所述。
SET @Colvalues = NULL;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(f.fieldName = ''',
f.fieldName, ''', COALESCE(v.fieldValue, f.defaultValue) , NULL)) AS ', '''', f.fieldName , '''')
) INTO @Colvalues
FROM customField AS f
INNER JOIN Customvalue AS v ON f.Id = v.customFieldId;
SET @sql = CONCAT('SELECT
u.*, v.relatedId, v.CreatedAt, ', @Colvalues , '
FROM customField AS f
INNER JOIN Customvalue AS v ON f.Id = v.customFieldId RIGHT JOIN User u on u.id = v.relatedId
GROUP BY v.relatedId, v.CreatedAt;');
PREPARE stmt
FROM @sql;
EXECUTE stmt;
现在将其视为CustomUser表,我需要运行类似
的查询select * from CustomUser where HOMEEMAIL like '%ab%' and JOINDATE like '%2010%' and SCHOOLING? like '%1%'
或
select * from CustomUser where HOMEEMAIL like '%ab%' and JOINDATE like '%2010%' and SCHOOLING? like '%1%' and LANDPHONENO? like '%0112%'
答案 0 :(得分:1)
您可以使用子查询对其进行包装,并进行所需的任何过滤:
SET @Colvalues = NULL;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(f.fieldName = ''',
f.fieldName, ''', COALESCE(v.fieldValue, f.defaultValue) , NULL)) AS ', '''', f.fieldName , '''')
) INTO @Colvalues
FROM customField AS f
INNER JOIN Customvalue AS v ON f.Id = v.customFieldId;
SET @sql = CONCAT('SELECT * FROM (SELECT
u.*, v.relatedId, v.CreatedAt, ', @Colvalues , '
FROM customField AS f
INNER JOIN Customvalue AS v ON f.Id = v.customFieldId RIGHT JOIN User u on u.id = v.relatedId
GROUP BY v.relatedId, v.CreatedAt)
AS s WHERE s.Homeemail = 456;'); -- here
PREPARE stmt
FROM @sql;
EXECUTE stmt;
的 SqlFiddleDemo
强>
您还可以将条件提取到第二个变量并且只是连接:
SET @conditions = NULL;
SET @conditions = CASE WHEN @conditions IS NULL THEN '1 = 1' ELSE @conditions END
SET @sql = CONCAT('SELECT * FROM (SELECT
u.*, v.relatedId, v.CreatedAt, ', @Colvalues , '
FROM customField AS f
INNER JOIN Customvalue AS v ON f.Id = v.customFieldId RIGHT JOIN User u on u.id = v.relatedId
GROUP BY v.relatedId, v.CreatedAt)
AS s WHERE ', @conditions); -- here