我必须通过许多标签订购一些项目,提取不同的项目ID, 数据如下:
样本数据
now()
我想提取ItemTag优先级ASC排序的Item id, 查询类似于错误一个:
Item:
id name creation
1 item1 2017-06-26 16:48:54
2 item2 2017-06-23 16:48:54
3 item3 2017-06-29 16:49:42
4 item4 2017-06-15 16:50:31
5 item5 2017-06-09 16:50:44
6 item6 2017-06-12 16:50:57
ItemTag:
id priority
1 10
2 999
3 15
4 8
ItemHasItemTag:
itemId itemTagId
1 1
1 2
2 1
2 3
3 4
4 1
4 4
5 1
5 2
5 3
6 2
结果:
SELECT i.id,
group_concat(it.priority order by priority asc) as tagPriorities
FROM Item i
JOIN ItemHasItemTag ihit on i.id = ihit.itemId
JOIN ItemTag it on it.id = ihit.tagId
GROUP BY i.id
ORDER BY it.priority asc;
我想要的结果应该是:
itemId (tagPriorities)
3 8
1 10,999
2 10,15
4 8,10
5 10,15,999
6 999
当然,由于小组by在之前执行,它会搞乱订单
有人可以帮助我吗?
我附上了创建架构:
itemId (tagPriorities)
3 8
4 8,10
2 10,15
5 10,15,999
1 10,999
6 999
答案 0 :(得分:1)
这能满足您的需求吗?
select
itempri.itemid
from (
select
ihit.itemid,
min(it.priority) as pri
from
itemhasitemtag as ihit
inner join itemtag as it on it.id=ihit.itemid
group by
ihit.itemid
) as itempri
order by
pri;
编辑:
要按升序排列所有优先顺序,您可能需要这样的内容:
select
ihit.itemid,
group_concat(lpad(cast(it.priority as character(8), 8, '0')), order by it.priority separator ', ') as pristr
from
itemhasitemtag as ihit
inner join itemtag as it on it.id=ihit.itemid
group by
ihit.itemid
order by
pristr;
(未测试的)