0

我正在使用以下查询:

SELECT `submit_time` AS 'Submitted',
 max(if(`field_name`='your-name', `field_value`, null )) AS 'your-name',
 max(if(`field_name`='your-email', `field_value`, null )) AS 'your-email',
 max(if(`field_name`='your-phone', `field_value`, null )) AS 'your-phone',
 max(if(`field_name`='Submitted From', `field_value`, null )) AS 'Submitted From',
 GROUP_CONCAT(if(`file` is null or length(`file`) = 0, null, `field_name`)) AS 'fields_with_file'
FROM `wp_cf7dbplugin_submits` 
WHERE `form_name` = 'test form'  
GROUP BY `submit_time` 
ORDER BY `submit_time` DESC
LIMIT 0,100

这让我返回了前 100 行(所有字段值都存在)。

我想要的是获得一个特定的行。为此,我在 WHERE 子句部分的上面的查询中附加了这一行( AND field_name='your-email' AND field_value = 'test@gm.com')。现在最终的查询是:

SELECT `submit_time` AS 'Submitted',
 max(if(`field_name`='your-name', `field_value`, null )) AS 'your-name',
 max(if(`field_name`='your-email', `field_value`, null )) AS 'your-email',
 max(if(`field_name`='your-phone', `field_value`, null )) AS 'your-phone',
 max(if(`field_name`='Submitted From', `field_value`, null )) AS 'Submitted From',
 GROUP_CONCAT(if(`file` is null or length(`file`) = 0, null, `field_name`)) AS 'fields_with_file'
FROM `wp_cf7dbplugin_submits` 
WHERE `form_name` = 'test form'  AND field_name=your-email AND field_value = 'test@gm.com'
GROUP BY `submit_time` 
ORDER BY `submit_time` DESC

但它只返回您的电子邮件值,其他字段值变为 NULL(就像您的姓名字段为 NULL)。

有谁知道如何做到这一点/我可以在哪里找到解决方案?

4

1 回答 1

2

您开始的查询是一个摘要查询(它有一个GROUP BY子句和一堆聚合函数,如MAXand GROUP_CONCAT)。您要查询的表是标签值表。也就是说,行包含

 submit-time    form-name   field-name    field-value
   (time)      test-form    your-email      test@gm.com
   (time)      test-form    your-name       Priya the Tester

等等。您开始查询的目的是“透视”该表,即将其转换为具有这样行的结果集。它通过使用关联表中的各个行来实现GROUP BY submit-time(这在繁忙的系统中是一种非常糟糕的方法,但没关系)。旋转的行看起来大致像这样。

    submit-time your-email     your-name
     (time)      test@gm.com   Priya the tester

因此,要仅选择此“结果”中的一个“行”,您需要比仅过滤原始表的行更聪明一些。你可以试试

 SELECT * 
   FROM (
       /* the entire original query */
         ) AS pivoted
  WHERE pivoted.`your-email` = 'test@gm.com'

它不会非常有效,但它会起作用。

于 2013-12-19T13:12:00.720 回答