[英]SQL Select two max rows from same table and joining with third table
混合中的两个表格:
项目
| 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
任何接受者? 您的意见非常感谢。
谢谢!
怎么样...
SELECT i.*
, x.detail last_detail
, y.detail last_non_ignored_detail
FROM items i
LEFT
JOIN
( SELECT a.*
FROM item_detail a
JOIN
( SELECT item_id
, MAX(id) max_id
FROM item_detail
GROUP
BY item_id
) b
ON b.item_id = a.item_id
AND b.max_id = a.id
) x
ON x.item_id = i.item_id
LEFT
JOIN
( SELECT a.*
FROM item_detail a
JOIN
( SELECT item_id
, MAX(id) max_id
FROM item_detail
WHERE ignored = 0
GROUP
BY item_id
) b
ON b.item_id = a.item_id
AND b.max_id = a.id
) y
ON y.item_id = i.item_id;
... 或类似的东西。
哦,傻我......
SELECT i.*
, MAX(d.detail) x
, MAX(CASE WHEN d.ignored = 0 THEN d.detail END) y
FROM items i
JOIN item_detail d
ON d.item_id = i.item_id
GROUP
BY item_id;
请注意,IGNORE是一个保留字,所以我改变了它。 (我冒昧地改变了戈登的答案!)
最简单的方法是使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.