I have this two tables,
--
-- Table structure for table `t1`
--
CREATE TABLE `t1` (
`pid` varchar(20) collate latin1_general_ci NOT NULL,
`pname` varchar(20) collate latin1_general_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Dumping data for table `t1`
--
INSERT INTO `t1` VALUES ('p1', 'pro1');
INSERT INTO `t1` VALUES ('p2', 'pro2');
-- ------------------------------------------开发者_Python百科--------------
--
-- Table structure for table `t2`
--
CREATE TABLE `t2` (
`pid` varchar(20) collate latin1_general_ci NOT NULL,
`year` int(6) NOT NULL,
`price` int(3) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Dumping data for table `t2`
--
INSERT INTO `t2` VALUES ('p1', 2009, 50);
INSERT INTO `t2` VALUES ('p1', 2010, 60);
INSERT INTO `t2` VALUES ('p3', 2007, 200);
INSERT INTO `t2` VALUES ('p4', 2008, 501);
my query is,
SELECT *
FROM `t1`
LEFT JOIN `t2` ON t1.pid = t2.pid
Getting the result,
pid pname pid year price
p1 pro1 p1 2009 50
p1 pro1 p1 2010 60
p2 pro2 NULL NULL NULL
My question is, i want to get the price value is 0 instead of NULL. How can i write the query to getting the price value is 0.
Thanks in advance for help.
you need to use IFNULL
SELECT pid,pname,pid,year,IFNULL(price,0)
FROM `t1`
LEFT JOIN `t2`
ON (t1.pid = t2.pid)
IFNULL(field_to_test, value_to_show) will return 'value_to_show' when the field 'field_to_test' is null, when field_to_test is not null, it is returned directly.
精彩评论