1
items table(the users will select and store into mysql

itemID | name   | item 
1      | Mary   | pants, jeans
2      | John   | jacket, shirt
3      | Jack   | jacket, shirt

description table 

descID | item         
1      | jacket, shirt
2      | pants, jeans  
3      | dress, jeans 

comment table (retrieve the no of comments made)
commentId| item          | comment
1        | jacket        | great
2        | jacket        | nice
3        | jeans         | comfortable

如何从评论表示例中检索评论数,约翰登录。它应该检索 2。

到目前为止,我有这个 SQL 语句:

SELECT DISTINCT(COUNT(comment)) AS comment
FROM comment co
INNER JOIN item i
WHERE co.item = i.item; 
4

2 回答 2

1

您应该使用外键而不是文本字符串来关联您的表。答案是修复你的桌子设计。

看来您想要用户和项目之间的多对多关系。这需要另一个表来存储多对多关联。

用户:

ID     | name
1      | Mary
2      | John
3      | Jack

项目:

ID     | description         
1      | jacket
2      | pants  
3      | dress
4      | shirt
5      | jeans

用户项目关联:

UserID | ItemID
1      | 2
1      | 5
2      | 1
2      | 4
3      | 1
3      | 4

注释:

ID       | itemID        | comment
1        | 1             | great
2        | 1             | nice
3        | 5             | comfortable

您的查询将是:

select count(distinct c.ID) from 
Users as u JOIN UserItemAssoc as uaa on (u.id = uaa.userID)
JOIN Items as i on (i.ID = uaa.itemID)
JOIN Comments as c on (c.itemID = i.ID)
WHERE u.Name = 'John'
于 2013-01-10T05:41:58.097 回答
0

尝试这个:

SELECT COUNT(DISTINCT c.comment) AS commentCount 
FROM comment c 
INNER JOIN item i ON FIND_IN_SET(c.item, i.item) 
WHERE i.name = 'John';
于 2013-01-10T05:20:56.650 回答