php – MySQL:链接评论的答案,分组和限制

我有以下MySQL表:

 +----+--------+------+
 | id | answer | type |
 +----+--------+------+
>| 1  | -1     | 1    |
 | 2  |  1     | 2    |
 | 3  |  1     | 1    |
>| 4  | -1     | 2    |
 | 5  |  4     | 2    |
 | 6  |  4     | 1    |
>| 7  | -1     | 1    |
 | 8  |  7     | 2    |
>| 9  | -1     | 2    |
>| 10 | -1     | 1    |
>| 11 | -1     | 2    |
 +----+--------+------+
 > = original comment

> answer = -1的条目是原始注释.
>带答案的条目!= -1是具有相应ID的评论的答案.
>此外,还有一些评论类型(在这种情况下为1或2).

现在我想检索原始注释(对于指定的类型和指定的限制)及其答案(类型和限制无关紧要).此外,将结果按两种类型分组会很棒(同样,只有原始注释的类型对分组很重要).

type = 1和limit = 2的查询结果应该类似(尚未分组):

 +----+--------+------+
 | id | answer | type |
 +----+--------+------+
>| 1  | -1     | 1    |
 | 2  |  1     | 2    |
 | 3  |  1     | 1    |
>| 7  | -1     | 1    |
 | 8  |  7     | 2    |
 +----+--------+------+

我现在已经尝试了几种小时的查询,我可以在没有程序的情况下实现它吗?程序会是什么样的?

我非常感谢你的帮助.

解决方法:

使用子查询首先获得类型1的2个原始注释,然后再次加入表以获取原始注释和响应.

select b.*
from (
  select id
  from answers
  where type = 1 and answer = -1
  limit 2) a
join answers b on a.id = b.id or a.id = b.answer;

fiddle

要选择每种类型的2条原始注释,您需要使用用户定义的变量来索引每条原始注释.以下代码将第一个原始注释索引为1,将第二个注释索引为2,依此类推,然后在类型更改时重置为1.最后在最后的where语句中筛选出大于2的索引.

select b.*, a.idx
from (
  select id, @idx:=if(@type=a.type,@idx+1,1) idx, @type:=a.type
  from (select id, type from answers2 where answer is null order by type) a
  join (select @type:=null, @idx:=null) b) a
join answers2 b on a.id = b.id or a.id = b.answer
where a.idx <= 2;

fiddle

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...