-1

如果值不为空,我尝试将表中的 3 列合并为一列。这是我的桌子:

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;

我尝试加入 username_l、username_u、username_a,因为只有一个有值!= null。

有人可以帮助我吗?

4

2 回答 2

1

如果您只想检索CONCAT生成的值,您可以这样做:

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

但是,如果您想将其存储在新列中username,请先添加列:

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

然后使用类似这样的 UPDATE 语句:

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

要加入,你可以尝试这样的事情:

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` , '' )
            )

链接:CONCATIFNULL

于 2013-11-09T23:20:24.743 回答
0

JOIN是一个技术术语,意思是两个表之间的交叉引用。听起来您只是想选择一个非空值,如下所示:

SELECT IFNULL(`username_l`, IFNULL(`username_u`, `username_a`)) AS `username`
FROM `roles_map`
WHERE IFNULL(`username_l`, IFNULL(`username_u`, `username_a`)) = 'admin'
于 2013-11-09T22:49:05.313 回答