如何检索没有评论?

时间:2013-01-10 03:58:05

标签: mysql sql select count

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

如何检索注释表示例中的注释,John登录。它应该检索2.

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

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

2 个答案:

答案 0 :(得分:1)

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

您似乎希望用户和项目之间存在多对多关系。这需要另一个表来存储多对多关联。

用户:

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

项目:

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

UserItemAssoc:

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'

答案 1 :(得分: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';