我有一个像下面的桌子============item | tag-----+------111 | amaretto-----+------111 | blueberry-----+------222 | amaretto-----+------333 | blueberry-----+------333 | chocolate-----+------444 | chocolate-----+------444 | amaretto-----+------555 | chocolate-----+------666 | blueberry-----+------666 | amaretto-----+------666 | chocolate============item和tag列共同构成一个复合主键。让我们想象一下,该项目像冰淇淋一样,而标签像是可用的口味。例如,如果我搜索amaretto(以冰淇淋为例),我想显示所有可用的amaretto冰淇淋组合,例如amaretto,amaretto + chocolate,blueberry + amaretto等。如果我搜索标签,我想显示所有可能的组合,例如;amaretto (222)amaretto,blueberry (111)amaretto,chocloate (444)amaretto,blueberry,chocolate (666)并且组合amaretto和amaretto,blueberry是相同的。我怎样才能做到这一点?我需要其他桌子吗?我使用PHP + MySQL。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 SELECT GROUP_CONCAT(DISTINCT a.tag) tags FROM my_table a JOIN my_table b ON b.item = a.item WHERE b.tag = 'amaretto' GROUP BY a.item;+------------------------------+| tags |+------------------------------+| amaretto,blueberry || amaretto || amaretto,chocolate || amaretto,blueberry,chocolate |+------------------------------+4 rows in set (0.00 sec)为了解决OP的修订问题,在同一查询中将DISTINCT和GROUP BY的罕见实例结合在一起...:SELECT DISTINCT GROUP_CONCAT(a.tag ORDER BY a.tag) tags FROM mytable a JOIN mytable b ON b.item = a.item AND b.tag <= a.tag WHERE b.tag = 'amaretto' GROUP BY a.item;+-------------------------------------+| tags |+-------------------------------------+| amaretto,blueberry || amaretto || amaretto,chocolate || amaretto,blueberry,chocolate || amaretto,blueberry,chocolate,pastry |+-------------------------------------+5 rows in set (0.01 sec)注意,多个相同的组合可能是缺乏归一化的症状。关于php - 如何从标签和项目表中获取所有可能的组合?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33890365/ (adsbygoogle = window.adsbygoogle || []).push({});
10-09 00:25