直接上图:
需要对查询结果进行group by
如果sn内有combine=2的,显示combine=2对应attr_value不同项,否则,一个sn内只显示一条。不想把group by 写的太复杂,不考虑case when。求方案(sql或者表设计方面的)
需要对查询结果进行group by
如果sn内有combine=2的,显示combine=2对应attr_value不同项,否则,一个sn内只显示一条。不想把group by 写的太复杂,不考虑case when。求方案(sql或者表设计方面的)
上面的数据没有太强的代表性,我来写一段吧id gid name sn combine attr_id attr_name attr_value
1 1 灰色坎肩 1 2 1 颜色 灰色
2 1 灰色坎肩 1 1 2 尺寸 x
3 2 红色坎肩 1 2 1 颜色 红色
4 2 红色坎肩 1 1 2 尺寸 xl
5 3 红色坎肩 1 2 1 颜色 红色
6 3 红色坎肩 1 1 2 尺寸 xxl7 4 衬衫xl 2 1 2 尺寸 xl
8 5 衬衫xxl 2 1 2 尺寸 xxl9 6 上衣xxx 3 null null null null这样最终显示出来的是4条:
id:1,3,7,9
根据sn进行归并,相同的sn内,如果有combine=2的,就按attr_value进行归并,
所以id=5和id=3的颜色值是一样的,所以id=5就不显示了。如果combine!=2,sn内就只显示一条记录。如id=7和id=8只显示一个
SELECT attr_value,min(id) as mi from tta a where exists(select 1 from tta b where a.sn=sn and b.combine=2
) and a.combine=2 group by attr_value) c on a.id=c.mi and a.attr_value=c.attr_value
union all
SELECT * from tta a where not exists(select 1 from tta where a.sn=sn and (combine=2 or a.id>id))
) and a.combine=2
union all
SELECT * from tta a where not exists(select 1 from tta where a.sn=sn and (combine=2 or a.id>id))
SELECT * from tta a where
(not exists(select 1 from tta b where a.sn=sn and b.combine=2 and a.attr_value=attr_value and a.id>id
) and a.combine=2 )
or
not exists(select 1 from tta where a.sn=sn and (combine=2 or a.id>id))
谢谢!
这个sql和后面两个sql得到的记录数与时间都不一样。
在表结构上面还可以优化设计以简化sql吗?
没有了,8楼的应该是简化一些的SQL