我有一个像这样的MySQL表:
MYTABLE
|-------------|
| ID | COLOR |
|----|--------|
| 01 | WHITE |
| 01 | BLACK |
| 01 | YELLOW |
| 02 | RED |
| 02 | BLUE |
| 02 | YELLOW |
| 03 | BLACK |
| 03 | BLUE |
| 03 | YELLOW |
|-------------|
当我想从ID获取所有颜色时,我执行此查询:
SELECT `COLOR` FROM `MYTABLE` WHERE `ID` = 2
RESULT
|--------|
| COLOR |
|--------|
| RED |
| BLUE |
| YELLOW |
|--------|
我怎样才能知道表中每种颜色的存在次数?
我必须执行哪些查询才能获得以下结果?
HOW CAN I GET THIS?
|----------------|
| COLOR | COUNT |
|--------|-------|
| RED | 1 |
| BLUE | 2 |
| YELLOW | 3 |
|----------------|
提前致谢。
答案 0 :(得分:3)
SELECT
COLOR,
count(*) as `COUNT`
From
MYTABLE
GROUP BY COLOR;
如果每个ID有多种颜色,您可以在Where ID = 2
之前添加group by
的条件
现在,如果您需要查找每种颜色在表格中出现的总时间而不考虑ID,然后使用ID过滤数据,那么您可以使用以下
select
t1.COLOR,
cnt as `count`
from MYTABLE t1
inner join (
select
COLOR,
count(*) as cnt
from MYTABLE
group by COLOR
)t2
on t2.COLOR = t1.COLOR
where t1.id = 2
<强> DEMO 强>