在使用數(shù)據(jù)庫查詢時授霸,很多時候為了省事會使用select * from table ...方式處理召娜,后續(xù)如果需要將* 號改成具體的列明時闸与,對于字段特別多的表恰力,如果通過手動一個一個寫的話效率會比較低锥债,可以使用group_concat內(nèi)置函數(shù)進(jìn)行逗號拼接獲取*號對應(yīng)的所有字段列名陡蝇,如下所示:
查看表字段列:
descorder_info;
獲取拼接字段列:
-- 默認(rèn)逗號分隔,其中table_schema為數(shù)據(jù)庫名哮肚,table_name為表名selectgroup_concat(COLUMN_NAME)asrfrominformation_schema.columnswheretable_schema="test"andtable_name="order_info";
如果表名需要別名的話登夫,通過concat函數(shù)給列明加上即可:
-- 默認(rèn)逗號分隔,加上別名前綴selectgroup_concat(concat("alia.", COLUMN_NAME))asrfrominformation_schema.columnswheretable_schema="test"andtable_name="order_info";
如果想在逗號前加上一個空格的話可以設(shè)置分隔符:
-- 按制定分隔符分隔,逗號后加一個空格 selectgroup_concat(COLUMN_NAME SEPARATOR ", ")asrfrominformation_schema.columnswheretable_schema="test"andtable_name="order_info";
若果不需要一些字段的話可以再where條件里加上不想要的字段列:
-- 過濾不想要的字段 selectgroup_concat(COLUMN_NAME SEPARATOR ", ")asrfrominformation_schema.columnswheretable_schema="test"andtable_name= "order_info" andCOLUMN_NAME not in('create_date','pay_date');
以此方式便可很好地將*替換成左右字段名拼接效果