我有一张桌子;汽车
汽车有很多领域:颜色,品牌,型号,坠毁等等
我查询表格:
从颜色为红色的汽车中选择所有
然后,我想查询该结果,计算有多少已崩溃。 (崩溃的字段是布尔值)
所以最后,我应该拥有的数据是红色汽车的所有字段,并且知道x已经崩溃了
是否可以在mysql门只敲一次? 或者你必须做两个单独的查询?
感谢
答案 0 :(得分:2)
一些数据:
mysql> select * from cars;
+-----+-------+---------+
| SNO | color | crashed |
+-----+-------+---------+
| 1 | red | 0 |
| 2 | red | 1 |
| 3 | red | 1 |
| 4 | blue | 1 |
| 5 | blue | 1 |
| 6 | blue | 1 |
| 7 | blue | 0 |
+-----+-------+---------+
和查询:
mysql> select color,sum(crashed),count(*) as total from cars group by color;
+-------+--------------+-------+
| color | sum(crashed) | total |
+-------+--------------+-------+
| blue | 3 | 4 |
| red | 2 | 3 |
+-------+--------------+-------+
2 rows in set (0.00 sec)
答案 1 :(得分:0)
您可以尝试:
SELECT * FROM cars WHERE color = "red" AND crashed = TRUE
或者无论你的崩溃指标是什么,我都只使用过SQL,但我相信 此查询将显示所有红色车辆,并且崩溃值为true。
答案 2 :(得分:0)
是的,你会使用WHERE
条款。
SELECT * FROM cars WHERE Color = 'red' AND Crashed = true
或者如果你想按颜色崩溃,
SELECT color, count(*) FROM Cars WHERE crashed = true GROUP BY color;
或者,正如您澄清的那样,SELECT crashed, count(*) as yourval FROM Cars WHERE color = 'Red' GROUP BY crashed