mysql - 查询是否可能不存在任何组值,但为其行返回 null?

标签 mysql sql

我正在尝试进行民意调查,首先这是我的表格

投票表

[pid][title][choices]

选择是动态的,至少需要2个选择,它是用分隔符构造的

示例:

'Apple|Grape|Banana'

另一个表是响应表,我在其中存储用户响应

[pid][uid][answer]

示例数据:

1-1-1 //where pid - uid - answer
1-2-1
1-3-2
1-4-3
1-5-3

使用此查询我可以获得每个答案的响应数

SELECT `answer`, COUNT(`answer`) as 'response' 
FROM `poll_response` WHERE `pid` = 1 GROUP BY `answer`

结果

[ answer ][ response ]
[    1   ][     2    ]
[    2   ][     1    ]
[    3   ][     2    ]

效果很好,除非某个选项没有受访者

示例:

1-1-1
1-2-1
1-3-1
1-4-3
1-5-3

这会给我

[ answer ][ response ]
[    1   ][     3    ]
[    3   ][     2    ]

但我需要的是

[ answer ][ response ]
[    1   ][     3    ]
[    2   ][     0 or null    ]
[    3   ][     2    ]

我知道如果每个选项都有自己的列,则可以通过 LEFT JOIN 到 POLL 表来完成,但选项是动态的,它可以超过 10 或任何 X。

当前的设置可以吗?有什么想法吗?

最佳答案

您的问题中有两个有趣的问题。一是如何确定选择的数量,二是如何生成数字序列,而无需创建可用于查找“缺失”答案的表格。

首先,一些字符串操作可以帮助您。如果分隔符始终为“|”那么表达式 length(choices)-length(replace(choices,"|",""))+1 将为您提供民意调查的选项数量。

关于第二个问题,可能有一种方法使用内联变量(@row等)来生成序列,但在有有限最大选择集的情况下,更简单的方法可能是简单的联合,例如,沿着 select 1 as counter union select 2 union select 3 union select 4 union select 5 的思路。

结合以上内容,从响应表中查找序列中未收到响应且 不存在 的项目。使用字符串表达式将序列中的项目限制为小于给定轮询可用的最大选项数的项目。例如:

select counter as answer, 0 as response
from polltable p,
  (select 1 as counter union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) as options
where p.pid=1
  and not exists (
    select answer from response r
    where r.pid=1
      and answer=counter)
  and counter<=length(choices)-length(replace(choices,"|",""))+1

最后,将包含已回答选项的初始查询与上述查询合并。这是一个示例 sql fiddle .

关于mysql - 查询是否可能不存在任何组值,但为其行返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25781484/

相关文章:

MySQL - 检查连续列是否相同并仅显示那些行

mysql - 当数据不存在时返回 NULL 或空值

php - CakePHP 查询 - 复杂的 AND/OR 条件

php - 在网站上显示一些统计信息的最佳方式?

sql - 使用sql从excel表格中获取数据

java - 如何在抛出异常后促使应用程序继续运行?

mysql - 远程连接 Mysql Ubuntu

mysql - 创建临时表时出错

php - MySQL从同一个表中选择两行

php - 如何在mysql中存储动态生成的复选框的详细信息