您的位置:首页 > 数据库

sql语句多表查询大集合

2016-05-13 21:04 393 查看
<span style="font-size:18px;">--
-- 表的结构 `post`
--

CREATE TABLE IF NOT EXISTS `post` (
`user_id` int(10) NOT NULL AUTO_INCREMENT,
`info` text CHARACTER SET utf8 NOT NULL,
`time` varchar(30) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- 转存表中的数据 `post`
--

INSERT INTO `post` (`user_id`, `info`, `time`) VALUES
(1, '我是小诸葛', ''),
(2, '我是小诸葛2', ''),
(3, '我是小诸葛3', '');

-- --------------------------------------------------------

--
-- 表的结构 `user`
--

CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`username` varchar(30) NOT NULL DEFAULT '' COMMENT '用户名',
`password` varchar(30) NOT NULL DEFAULT '' COMMENT '密码',
`sex` char(2) NOT NULL DEFAULT '保密' COMMENT '性别',
`email` varchar(40) NOT NULL DEFAULT '' COMMENT '邮箱',
`hobby` varchar(255) NOT NULL DEFAULT '' COMMENT '兴趣爱好',
PRIMARY KEY (`id`),
KEY `username` (`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='用户表' AUTO_INCREMENT=8 ;

--
-- 转存表中的数据 `user`
--

INSERT INTO `user` (`id`, `username`, `password`, `sex`, `email`, `hobby`) VALUES
(1, 'apple', '123456', '男', 'apple@qq.com', '篮球'),
(2, 'orange', '123456', '男', 'orange@qq.com', '篮球'),
(3, 'bananer', '123456', '女', 'bananer@qq.com', '羽毛球'),
(4, 'bob', '123456', '男', 'bob@qq.com', '乒乓球'),
(5, 'coco', '123456', '男', 'coco@qq.com', '开船'),
(6, 'Lily', '123456', '女', 'Lily@qq.com', '游泳'),
(7, 'lucy', '123456', '女', 'lucy@qq.com', '台球');

方法一:
//查询出两张表【相同字段】的指定数据
select user.username,post.info from user,post where user.id=post.user_id;
//查询出两张表【相同字段】的指定的username
select user.username,post.info from user,post where user.id=post.user_id and user.username='apple';

方法二:左连接,右连接,内连接,查询
//左连接是把左边那个表指定字段全部查出来
select user.username,post.info from user left join post on user.id=post.user_id;
//右连接是把右边那个表指定字段全部查出来
select user.username,post.info from user right join post on user.id=post.user_id;
//内连接是把两个表的关联字段具有相同值的查出来(内连接和方法一结果相同)
select user.username,post.info from user inner join post on user.id=post.user_id;</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: