2012-11-16 14 views
6

Ich habe Mühe, dies zu lösen. Ich habe einen Tisch wie diesen.Auftrag von FIELD in MYSQL

+-------------+-------+ 
    | type  | COUNT | 
    +-------------+-------+ 
    | A   |  1 | 
    | C   |  5 | 
    | B   |  4 | 
    +-------------+-------+ 

Ich möchte die Tabelle abfragen und das Ergebnis muss so sein.

+-------------+-------+ 
| type  | COUNT | 
+-------------+-------+ 
| A   |  1 | 
| B   |  5 | 
| C   |  9 | 
| D   |  0 | 
+-------------+-------+ 

QUERY:

select type , COUNT from TABLE order by FIELD(type,'A','B','C','D') ; 

Es funktioniert gut, wenn die Spalte type Wert für 'A, B, C, D'. In einigen Fällen kann die Reihenfolge von FIELD('A','B','C','D') einige Spalten keinen Wert in der Tabelle haben. In diesem Fall möchte ich 0 setzen und ein Ergebnis konstruieren.

D ist nicht in der Tabelle. Also setze '0' dafür.

SHOW TABLE OUTPUT CREATE

CREATE TABLE `Summary` (
    `TIMESTAMP` bigint(20) NOT NULL DEFAULT '0', 
    `type` varchar(50) NOT NULL DEFAULT '', 
    `COUNT` bigint(19) NOT NULL, 
    PRIMARY KEY (`TIMESTAMP`,`type`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 
+0

können Sie das Schema der Tabelle schreiben? Ist die Tabelle mit 'type' und' count' eine Ergebnismenge oder die Originaltabelle selbst? –

+0

@JohnWoo Ich habe meine Show create table output gepostet. – kannanrbk

+0

warum nicht mit set count column Standardwert als 0 'COUNT' bigint (19) NOT NULL DEFAULT '0' – Sathish

Antwort

8

wie abt dies:

select a.col as type,coalesce (`COUNT`,0) as `count` 
from 
(select 'A' as col union all 
select 'B' as col union all 
select 'C' as col union all 
select 'D' as col)a 
left join Table1 T 
on a.col=T.type 
order by FIELD(a.col,'A','B','C','D') ; 


SQL fiddle demo