PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Tuesday, June 7, 2016

MySQL - For each Row Print Columns/Flags with value equal to 1


One of my colleague came to me with this problem. It enjoyed solving it. Here, it is for you. Say, you are given a table like this with a given number of columns.

   id  Flag_1  Flag_2  Flag_3  Flag_4  Flag_5
------  --------  -------  --------  --------  -------
    1       1       1       1       1         1
    2       0       0       0       0         0
    3       1       1       0       1         0
    4       0       1       0       0         1
    5       1       0       1       0         1

Desired output is to have a comma separated list of "Flag Names" that are ON for each row. i.e.

   id  onFlags                             
------  ------------------------------------
    1  Flag_1,Flag_2,Flag_3,Flag_4,Flag_5  
    2                                      
    3  Flag_1,Flag_2,Flag_4,               
    4  Flag_2,Flag_5                       
    5  Flag_1,Flag_3,Flag_5   

It's not a generally required to print column names as a result of query. One easy solution is to fetch data in sql and then use some programming language to manipulate it. However, try running sql only to fetch it. I recommend to minimize the browser and try it on your own.

=============================================

SELECT
 id, CONCAT(flag1, flag2, flag3, flag4,flag5) AS onFlags
FROM
 (SELECT
   IF(Flag_1 = '1', 'Flag_1,', '') AS flag1,
   IF(Flag_2 = '1', 'Flag_2,', '') AS flag2,
   IF(Flag_3 = '1', 'Flag_3,', '') AS flag3,
   IF(Flag_4 = '1', 'Flag_4,', '') AS flag4,
   IF(Flag_5 = '1', 'Flag_5', '') AS flag5,
   id
 FROM
   Flags) AS a ;

Wednesday, August 28, 2013

How to change timezone of server Fedora/Ubuntu/Linux

 ln -sf /usr/share/zoneinfo/Asia/Calcutta /etc/localtime


In place of Asia/Calcutta, select the time zone you want to set.

Thursday, November 15, 2012

jQuery check if an element with id exists

How would you if an element with particular id exists on the page?


$('#element').length == 0; // no element found