日期:2014-05-16  浏览次数:20749 次

如何把查询后没有的的字符填写成NULL

T1
a           b
1           11
2           22
3           33

T2
a           c
1           gg
2           hh
联合查询后,表应该是这样,应该写这句SQL呢
a             b             c
1           11           ggg
2           22           hhh
3           33           NULL

------解决方案--------------------

DROP DATABASE IF EXISTS `test`;
CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;

#
# Table structure for table t1
#

CREATE TABLE `t1` (
`a` int(11) NOT NULL auto_increment,
`b` varchar(10) default NULL,
PRIMARY KEY (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

#
# Dumping data for table t1
#

INSERT INTO `t1` VALUES (1, '11 ');
INSERT INTO `t1` VALUES (2, '22 ');
INSERT INTO `t1` VALUES (3, '33 ');

#
# Table structure for table t2
#

CREATE TABLE `t2` (
`a` int(11) NOT NULL auto_increment,
`c` varchar(10) default NULL,
PRIMARY KEY (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

#
# Dumping data for table t2
#

INSERT INTO `t2` VALUES (1, 'gg ');
INSERT INTO `t2` VALUES (2, 'hh ');


#应该能解决你的问题吧
select t1.a,t1.b,case when t2.c is null then '自己定义 ' else t2.c end from t1 left join t2 on t1.a=t2.a


借宝地求助:
http://community.csdn.net/Expert/topic/5565/5565142.xml?temp=2.009219E-02