sql语句多表查询大集合

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值