如果value不为null,我尝试将我的表中的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。
有人能帮助我吗?
答案 0 :(得分:1)
如果您只想检索CONCAT enated值,可以这样做:
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` , '' )
)
答案 1 :(得分: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'