我正在努力解决这个问题。我有这样一张桌子。
+-------------+-------+ | type | COUNT | +-------------+-------+ | A | 1 | | C | 5 | | B | 4 | +-------------+-------+
我想查询表,结果必须是这样。
+-------------+-------+ | type | COUNT | +-------------+-------+ | A | 1 | | B | 5 | | C | 9 | | D | 0 | +-------------+-------+
查询:
select type , COUNT from TABLE order by FIELD(type,'A','B','C','D') ;
如果该列的type值为’A,B,C,D’,则可以正常工作。在某些情况下,FIELD('A','B','C','D')某些列的顺序可能在table中没有价值。在这种情况下,我想为其设置0并构造一个结果。
type
FIELD('A','B','C','D')
表中没有D。因此,将其设置为“ 0”。
显示创建表输出
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
怎么这样:
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') ;