I have a query that is selecting about 20 columns, all are varchars.
Some will be empty, which is just fine. But I want to put a default string of "-------" for any columns that are empty.
Here's what I have so far, that works:
$sql = "SELECT col1, ";
$sql .= "IF(`col2` IS NULL,'----------',`col2`) AS `col2`, ";
$sql .= "IF(`col3` IS NULL,'----------',`col3`) AS `col3`, ";
$sql .= "IF(`col4` IS NULL,'----------',`col4`) AS `col4`, ";
$sql .= "IF(`col5` IS NULL,'----------',`col5`) AS `col5`, ";
$sql .= "IF(`col6` IS NULL,'----------',`col6`) AS `col6`, ";
.......and so on.....
$sql .= "FROM `tableName`";
This works for me, but I am wondering i开发者_如何学Cf there's a more "global" way, instead of specifying each column.
Perhaps a slightly less verbose way of achieving the same would be to use COALESCE in your SQL statement:
$sql = "SELECT col1, ";
$sql .= "COALESCE(col2,'----------'), ";
Not really a 'global' way though;
Perhaps having a table with many null columns is a pointer that database design could be improved eliminating the need for such global 'null' substitution.
Following mfloryan advice you can easily generate your string with a loop and implode() function
<?php
$sql = 'select col1,';
$a = array();
for ($i=2;$i<=20;$i++){
$a[] = "coalesce(col".$i.",'-----') as col".$i."\r\n";
}
$sql.=implode(',',$a);
$sql.=" from table_name";
echo $sql;
?>
edit. Note that information_schema is a wonderful tool to create dynamic SQL. This is an example
mysql> use test;
Database changed
mysql> create table dynSQL(
-> col1 varchar(10),
-> col2 varchar(10),
-> col3 varchar(10),
-> col4 varchar(10)
-> ) engine = myisam;
Query OK, 0 rows affected (0.04 sec)
mysql>
mysql> insert into dynSQL(col1,col2,col3,col4)
-> values (1,3,null,4),(10,null,4,null),(20,4,5,null);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql>
mysql> set @str = (select concat('select col1,',group_concat(concat("coalesce(",column_name,",'----') as ",column_name,"\n")),' from dynSQL')
-> from information_schema.columns
-> where table_schema = 'test' and table_name = 'dynSQL' and column_name like 'col%' and column_name <> 'col1');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare stmt from @str;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt;
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| 1 | 3 | ---- | 4 |
| 10 | ---- | 4 | ---- |
| 20 | 4 | 5 | ---- |
+------+------+------+------+
3 rows in set (0.00 sec)
mysql> deallocate prepare stmt;
Query OK, 0 rows affected (0.00 sec)
Regards. Nick
精彩评论