1

I'm building a MySQL tagging DB to allow users to tag products.

My current design uses these tables:

Account
id (PK)
username

Product
id (PK)
product_name

Product_Tag
id (PK)
product_id (FK to Product)
tag_id (FK to Tag)
account_id (FK to Account)
created_date

Tag
id (PK)
tag_name

Note in my design, I'm tracking which user tagged the product and when, and enabling a product to be tagged multiple times using the same tag so I know which tags are most popular for a given product.

I'm trying to figure out a tag search query that returns products most tagged to the searched tags. For example, if I query "red dress", products that are more heavily tagged with "red" and "dress" should appear towards the top in the result set. What query can accomplish this with my existing design?

4

3 に答える 3

1
select max(cnt) from(
    select count(*) cnt
    from product_tag
    where tag_id = <tag id of red dress>
    group by product_id);
于 2013-02-01T23:04:24.777 に答える
1

この問題は、Relational Division

SELECT  a.ID, a.ProductName
FROM    Product a
        INNER JOIN Product_Tag b
            ON a.ID = b.Product_ID
        INNER JOIN Tag c
            ON b.Tag_ID = c.ID
WHERE   a.ProductName IN ('RED','ADDRESS')
GROUP   BY a.ID, a.ProductName
HAVING  COUNT(*) >= 2
ORDER   BY COUNT(*) DESC
于 2013-02-02T01:45:23.677 に答える
0

これを試して:

SELECT
    P.id,
    P.product_name
FROM Product P
    LEFT JOIN Product_tag PT
        ON P.id = PT.product_id
    LEFT JOIN Tag T
        On PT.tag_id = T.id
WHERE T.tag_name = 'red'
     OR T.tag_name = 'dress'
GROUP BY P.id, P.product_name
ORDER BY COUNT(P.id) DESC

LIMIT最初にn最もタグ付けされた製品を取得するために使用することはできません。

于 2013-02-01T23:08:49.417 に答える