【发布时间】:2014-04-17 06:48:48
【问题描述】:
我在 MySQL 中使用多个表的子查询和 COUNT() 遇到问题。
例如,我有两个表:
t1
id | name
42 | John
22 | Mary
77 | Nick
t2
userid | merchandise | type
22 | Skirt | clothes
22 | Scarf | clothes
22 | Purse | clothes
77 | Grill | home
22 | Pen | office
42 | Jacket | clothes
我想通过使用两个表来计算表 2 中的 types。因此,例如,所需的输出将是:
为每位用户购买的衣服数量
name | count_clothes
Mary | 3
John | 1
Nick | 0
到目前为止我想出的最好的 MySQL 查询是:
SELECT t1.name, (
SELECT COUNT(*) FROM t2 WHERE type = 'clothes'
) as count_clothes
FROM users
ORDER BY count_clothes;
但它给我的输出是:
name | count_clothes
Mary | 3
John | 3
Nick | 3
我知道缺陷是我的 COUNT() 查询。我已经尝试匹配 ID 列,但它一直返回一个错误,说 子查询返回超过 1 行。
【问题讨论】:
-
您的子查询中没有
WHERE子句,所以它会计算所有内容。