我正在使用以下查询:
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)。
有没有人知道如何做到这一点/哪里可以找到解决方案?
答案 0 :(得分:2)
您开始的查询是摘要查询(它有一个GROUP BY
子句和一堆聚合函数,如MAX
和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'
它不会非常有效,但它会起作用。