MySQL获取具有按所包含属性数量排序的特定属性的项目

时间:2015-11-22 09:43:31

标签: mysql count distinct multiple-tables

我有3张桌子: 食物 -

id    name
1     pizza
2     pasta
3     salad

标签

id    tagName
1     spicy
2     non-spicy
3     healthy
4     cheesy

food_tag

id    food_id    tag_id
1     1          1
2     1          4
3     2          2
4     2          4
5     3          3
6     3          2

我想查询这三个表,以获得按最大匹配标记数排序的食品。因此,如果我查询带有标签的食物('辣'俗气'),我应该按顺序获得披萨和意大利面,但不是沙拉(因为它不含有任何相关的标签)。

我正在尝试这个查询,它没有给我我想要的结果:

SELECT a.name, COUNT(DISTINCT c.tagName) FROM food a, tags b, food_tag c
 WHERE b.tagName in ('spicy', 'cheesy') AND b.id = c.tag_id 
 AND a.id = c.food_id ORDER BY COUNT(DISTINCT c.tagName) DESC;

我想要的输出是:

a.name   count(distinct c.tagName)  
pizza    2
pasta    1

有谁能告诉我我的错误是什么?

1 个答案:

答案 0 :(得分:2)

<强>问题

  
      
  • a.name
  • 缺少群组   

调整后的查询

LIMIT = 20000

prima = []  #empty list

def Bsearch(lsta,low,high,search):   #Binary search function to search a prime number
    if low>high:
        return 0
    else:
        mid = int((low+high)/2)

        if search<lsta[mid]:
            Bsearch(lsta,low,mid-1,search)
        if search>lsta[mid]:
            Bsearch(lsta,mid+1,high,search)
        if search==lsta[mid]:
            return 1
    return 0

def primes(LIMIT):   #sieve to create prime numbers upto LIMIT
    dic = {}    #empty dictionary
    for i in range(2,LIMIT):
        dic[i] = 1
    for i in range(2,LIMIT):
        for j in range(i,LIMIT):
            if i*j>LIMIT:
                break
            dic[i*j] = 0
    for i in range(2,LIMIT):
        if dic[i]==1:
            prima.append(i)

primes(LIMIT)

result = []

<强>输出

SELECT a.name, COUNT(DISTINCT b.tagName) 
FROM food a, tags b, food_tag c 
WHERE b.tagName in ('spicy', 'cheesy') 
AND b.id = c.tag_id 
AND a.id = c.food_id 
group by a.name
ORDER BY COUNT(DISTINCT b.tagName) DESC
;

sqlfiddle