数据库
首页 > 数据库> > mysql – SQL从同一个表中选择两个最大行并与第三个表连接

mysql – SQL从同一个表中选择两个最大行并与第三个表连接

作者:互联网

混合中的两个表格:

项目

| item_id | user_id | data |
----------------------------
| 10       | 100    | A    |
| 11       | 100    | C    |
| 12       | 101    | E    |
| 13       | 101    | G    |

item_detail

| id | item_id | ignore | detail1 | detail2 | detail3 | detail4 |
-----------------------------------------------------------------
| 1  | 10      |   0    |   h1    |   h2    |  h3     |  h4     |
| 2  | 10      |   0    |   g1    |   g2    |  g3     |  g4     |
| 3  | 10      |   1    |   f1    |   f2    |  f3     |  f4     |
| 4  | 11      |   0    |   e1    |   e2    |  e3     |  e4     |
| 5  | 11      |   0    |   d1    |   d2    |  d3     |  d4     |
| 6  | 11      |   1    |   c1    |   c2    |  c3     |  c4     |
| 7  | 12      |   0    |   b1    |   b2    |  b3     |  b4     |
| 8  | 13      |   0    |   a1    |   a2    |  a3     |  a4     |

我需要通过item_id找到item_detail的MAX id中的detail1,detail2和item_id的item_detail的MAXNON IGNORED ID的detail3,detail4,并显示项目行.
预期结果:

| item_id | user_id | data | detail1 | detail2 | detail3 | detail4 |
--------------------------------------------------------------------
| 10      | 100     | A    |   f1    | f2      | g3      | g4      |       
| 11      | 100     | C    |   c1    | c2      | d3      | d4      |
| 12      | 101     | E    |   b1    | b2      | b3      | b4      |
| 13      | 101     | G    |   a1    | a2      | a3      | a4      |

这是带有这些数据集的SQLFiddle:http://sqlfiddle.com/#!2/52839
任何接受者?您的意见非常感谢.
谢谢!

解决方法:

最简单的方法是使用group_concat()和substring_index():

select i.item_id, i.user_id, i.data,
       substring_index(group_concat(id.detail order by id.id desc), ',', 1
                      ) as last_detail,
       substring_index(group_concat(case when id.ignored = 0 then id.detail1 end order by id.id desc), ',', 1
                      ) as last_non_ignored_detail1
       substring_index(group_concat(case when id.ignored = 0 then id.detail2 end order by id.id desc), ',', 1
                      ) as last_non_ignored_detail2
       substring_index(group_concat(case when id.ignored = 0 then id.detail3 end order by id.id desc), ',', 1
                      ) as last_non_ignored_detail3
       substring_index(group_concat(case when id.ignored = 0 then id.detail4 end order by id.id desc), ',', 1
                      ) as last_non_ignored_detail4
  from items i join
       item_detail id
       on i.item_id = id.item_id
 group by i.item_id;

标签:mysql,sql,greatest-n-per-group,aggregate-functions,sql-view
来源: https://codeday.me/bug/20190612/1224777.html