MySQL 显示低于限制值的总数
MySQL display total count of values under limit
我是 SQL 的新手,目前正在尝试 运行 一个查询,该查询将 return 某个值的总计数 (使用 phpmyadmin).
假设我们有一个 table 像这样:
CarID | Car | OwnerID
-------------------
1 | Name | 1
2 | Name | 3
3 | Name | 2
4 | Name | 1
现在我希望能够获得车主拥有的汽车总数,如果它低于 2 - 然后得到这个:
OwnerID| TotalCars |
---------------------
2 | 1 |
3 | 1 |
我将如何做到这一点?我的情况与我给出的示例略有不同,但它基本上是完全相同的目标,只是不同的数字和更多的记录。
当我尝试时,那些超过我希望看到的数字 return 的值为零??
(我的代码)
Code giving me trouble
(我的结果)
ID 6 has 3 properties so it shouldn't be showing me it at all and I don't understand why it's returning it as 0
您可以使用 GROUP BY
COUNT
和 HAVING
CREATE TABLE Table1
(`CarID` int, `Car` varchar(4), `OwnerID` int)
;
INSERT INTO Table1
(`CarID`, `Car`, `OwnerID`)
VALUES
(1, 'Name', 1),
(2, 'Name', 3),
(3, 'Name', 2),
(4, 'Name', 1)
;
SELECT `OwnerID`, COUNT(*) as countr
FROM Table1
GROUP BY `OwnerID`
HAVING countr < 2
OwnerID | countr
------: | -----:
3 | 1
2 | 1
db<>fiddle here
我是 SQL 的新手,目前正在尝试 运行 一个查询,该查询将 return 某个值的总计数 (使用 phpmyadmin).
假设我们有一个 table 像这样:
CarID | Car | OwnerID
-------------------
1 | Name | 1
2 | Name | 3
3 | Name | 2
4 | Name | 1
现在我希望能够获得车主拥有的汽车总数,如果它低于 2 - 然后得到这个:
OwnerID| TotalCars |
---------------------
2 | 1 |
3 | 1 |
我将如何做到这一点?我的情况与我给出的示例略有不同,但它基本上是完全相同的目标,只是不同的数字和更多的记录。
当我尝试时,那些超过我希望看到的数字 return 的值为零??
(我的代码) Code giving me trouble
(我的结果) ID 6 has 3 properties so it shouldn't be showing me it at all and I don't understand why it's returning it as 0
您可以使用 GROUP BY
COUNT
和 HAVING
CREATE TABLE Table1 (`CarID` int, `Car` varchar(4), `OwnerID` int) ; INSERT INTO Table1 (`CarID`, `Car`, `OwnerID`) VALUES (1, 'Name', 1), (2, 'Name', 3), (3, 'Name', 2), (4, 'Name', 1) ;
SELECT `OwnerID`, COUNT(*) as countr FROM Table1 GROUP BY `OwnerID` HAVING countr < 2
OwnerID | countr ------: | -----: 3 | 1 2 | 1
db<>fiddle here