为什么这个有趣的结果用这个mysql查询...?

时间:2012-12-28 05:33:44

标签: mysql select count group-by

这是我的桌子。

mysql> desc products;
+--------------------+-------------+------+-----+--------------------------------------+-------+
| Field              | Type        | Null | Key | Default                              | Extra |
+--------------------+-------------+------+-----+--------------------------------------+-------+
| productCode        | varchar(15) | NO   | PRI | NULL                                 |       |
| productName        | varchar(70) | NO   |     | NULL                                 |       |
| productUrl         | varchar(50) | YES  |     | NULL                                 |       |
| productLine        | varchar(50) | NO   |     | NULL                                 |       |
| productScale       | varchar(10) | NO   |     | NULL                                 |       |
| productVendor      | varchar(50) | NO   |     | NULL                                 |       |
| productDescription | text        | NO   |     | NULL                                 |       |
| quantityInStock    | smallint(6) | NO   |     | NULL                                 |       |
| buyPrice           | double      | NO   |     | NULL                                 |       |
| MSRP               | double      | NO   |     | NULL                                 |       |
| Image              | varchar(50) | YES  |     | phpGridx/SampleImages/motorcycle.jpg |       |
+--------------------+-------------+------+-----+--------------------------------------+-------+

当我尝试以下查询时..?

mysql> select productVendor,count(productCode) from products order by productCode;
+-----------------+--------------------+
| productVendor   | count(productCode) |
+-----------------+--------------------+
| Min Lin Diecast |                110 |
+-----------------+--------------------+

为什么会出现'Min Lin Diecast'。我的桌子上有大约11个其他的productVendors。为什么要这样,总行数是110就可以了,但我不明白为什么它特别显示供应商。 (它甚至不是第一张唱片)。

任何机构都能解释我为什么......

3 个答案:

答案 0 :(得分:3)

因为你没有GROUP BY子句导致它只有1条记录返回。

select productVendor,count(productCode) 
from products 
GROUP BY productVendor
order by productCode

如果在mysql中启用ONLY_FULL_GROUP_BY,则查询将不会执行。

答案 1 :(得分:2)

试试这个:

SELECT productVendor,count(productCode) 
FROM products 
GROUP BY productVendor
ORDER BY productCode;

答案 2 :(得分:0)

由于您没有在查询和SELECT语句中添加GROUP BY子句,因此您有两列productVendor和productCode,我的问题是,如果您只想知道productCode的数量,那么为什么选择productVendor列,因为总是productVendor value将是该列的第一个值。

因此,如果你想要所有productCode,productVendor的计数,你应该使用这个GROUP BY子句

     SELECT productVendor,count(productCode) 
     FROM   products 
     GROUP BY productVendor
     ORDER BY productCode