简体   繁体   English

从 MYSQL 数据透视表中过滤记录

[英]Filter records from MYSQL Pivot table

I have this query, http://sqlfiddle.com/#!9/1a579/3我有这个查询, http://sqlfiddle.com/#!9/1a579/3

I have built this using dynamic query.我使用动态查询构建了这个。 Need to know how can i filter records from it.需要知道如何从中过滤记录。 i need to consider the results of this query as a table.我需要将此查询的结果视为一个表。 lets say CustomUser table.让我们说 CustomUser 表。 so i need to query against this table like explained below.所以我需要像下面解释的那样查询这个表。

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;

This results has the following data,这个结果有以下数据, <code>在此处输入图片描述</code>

Now Considering this as CustomUser table, i need to run a query like现在将此视为 CustomUser 表,我需要运行一个查询

select * from CustomUser where HOMEEMAIL like '%ab%' and JOINDATE like '%2010%' and SCHOOLING? like '%1%'

or或者

select * from CustomUser where HOMEEMAIL like '%ab%' and JOINDATE like '%2010%' and SCHOOLING? like '%1%' and LANDPHONENO? like '%0112%'

You can wrap it with subquery and do any filtering you need:您可以使用子查询包装它并执行您需要的任何过滤:

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

You can also extract condition to second variable and just concatenate:您还可以将条件提取到第二个变量并连接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM