Question

i try to join 3 column from my table into one, if value is not null. this is my table:

CREATE TABLE IF NOT EXISTS `roles_map` (
  `rm_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username_a` varchar(45),
  `username_l` varchar(45),
  `username_u` varchar(45),
  `password` varchar(45) NOT NULL,
  `role_id` int(1) NOT NULL,
   PRIMARY KEY (`rm_id`),
   FOREIGN KEY (username_u) REFERENCES users(index_num),
   FOREIGN KEY (username_a) REFERENCES admins(login),
   FOREIGN KEY (username_l) REFERENCES lecturers(id_number),
   FOREIGN KEY (role_id) REFERENCES roles_name(role_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

i try to join username_l, username_u, username_a, because only one have value != null.

can somebody help me?

Was it helpful?

Solution 2

JOIN is a technical term, meaning a cross-reference between two tables. It sounds like you are just trying to select the one non-null value, like this:

SELECT IFNULL(`username_l`, IFNULL(`username_u`, `username_a`)) AS `username`
FROM `roles_map`
WHERE IFNULL(`username_l`, IFNULL(`username_u`, `username_a`)) = 'admin'

OTHER TIPS

If you just want to retrieve the CONCATenated value , you could do like this :

SELECT
    CONCAT(
         IFNULL( `username_a` , '' )
        ,IFNULL( `username_l` , '' )
        ,IFNULL( `username_u` , '' )
    )
FROM `roles_map`

But if you want to store it in a new column say username , first add the column :

ALTER TABLE `roles_map` ADD `username` VARCHAR( 45 ) NOT NULL DEFAULT '';

Then use an UPDATE statement something like this :

UPDATE `roles_map`
    SET `username` =
        CONCAT(
             IFNULL( `username_a` , '' )
            ,IFNULL( `username_l` , '' )
            ,IFNULL( `username_u` , '' )
        )

To JOIN you could try something like this :

SELECT
    `roles_map`.*
    ,CONCAT(
         IFNULL( `username_a` , '' )
        ,IFNULL( `username_l` , '' )
        ,IFNULL( `username_u` , '' )
    ) AS username
FROM
    `roles_map`
    LEFT OUTER JOIN
        `admins` ON
            `admins`.`login` = 
            CONCAT(
                 IFNULL( `roles_map`.`username_a` , '' )
                ,IFNULL( `roles_map`.`username_l` , '' )
                ,IFNULL( `roles_map`.`username_u` , '' )
            )

Links : CONCAT , IFNULL

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top