2015-11-25 41 views
1

我有像下面如何从单个表中找到类似的标签链接?

===================== 
item| flavor 
====+================ 
111 | amaretto 
111 | blueberry 
222 | amaretto 
333 | blueberry 
333 | chocolate 
444 | chocolate 
444 | amaretto 
555 | chocolate 
666 | blueberry 
666 | amaretto 
666 | chocolate 
777 | pastry 
777 | blueberry 
777 | amaretto 
777 | chocolate 
888 | amaretto 
888 | chocolate 
999 | chocolate 
999 | blueberry 
999 | amaretto 
101 | amaretto 
101 | blueberry 
===================== 

item一个表指示的冰淇淋名称和flavor列显示其中包含的风味组合。如果我没有必要的话,我想让我的数据库返回备用冰淇淋。例如,如果我正在查看项目111,我需要111101,它们具有完全相同的风味组合。我有一个像这样的查询;

SELECT item 
FROM `mytable` 
GROUP BY item 
HAVING SUM(tag = 'amaretto') > 0 
    AND SUM(tag = 'blueberry ') > 0 

但它返回的结果像;

111 
666 
777 
999 
101 

这是因为所有这些记录都amaretto和他们blueberry。但是对于666,777999,其中还有其他味道。我不想显示它们。相反,我只想要111广告101。有什么办法可以做到这一点?我是否需要额外的表格/我可以使用我当前的模式来实现吗?我使用PHP + MySQL。

谢谢。

回答

1
SELECT item 
FROM `mytable` 
GROUP BY item 
HAVING SUM(tag = 'amaretto') > 0 
    AND SUM(tag = 'blueberry ') > 0 
    and sum(tag not in ('amaretto','blueberry ')) = 0 

I.e.添加sum(tag not in ('amaretto','blueberry ')) = 0以确保不包含其他口味。

0

通过聚合函数GROUP_CONCAT,您可以获得每个项目的风味列表。然后您可以查找重复列表并显示关联的项目列表。

select flavors, group_concat(item order by item) as items 
from 
(
    select item, group_concat(tag order by tag) as flavors 
    from mytable 
    group by item 
) items_with_flavorlist 
group by flavors 
having count(*) > 1; 
相关问题