如何实现这样一个显示,一对多的关系

redcn2004 2015-12-14 08:06:10
表 test1
PID NUM
1 30


表test2
SID NUM1 PID
2 10 1
3 30 1

表test2 的外键为 PID ,为test1的主键,现在要得到以下的表,

PID NUM SID NUM1
1 30 2 10
0 0 3 30

即父表和子表联合起来,但是父表仅需显示一行,子表全部显示。
...全文
193 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
redcn2004 2015-12-17
  • 打赏
  • 举报
回复
虽非本意,但还是给几位热情的大侠点赞
redcn2004 2015-12-15
  • 打赏
  • 举报
回复
引用 1 楼 a346322359 的回复:
create table test1(pid int, num int); insert into test1 values (1,30); create table test2(sid int, num int,pid int); insert into test2 values (2,10,1),(3,30,1); select test1.pid,test1.num,test2.sid,test2.num from test1,test2 where test1.pid=test2.pid; 这样子吗?
有很多这样的记录 你这样联合 ,父表记录都填上了
redcn2004 2015-12-15
  • 打赏
  • 举报
回复
引用 1 楼 a346322359 的回复:
create table test1(pid int, num int); insert into test1 values (1,30); create table test2(sid int, num int,pid int); insert into test2 values (2,10,1),(3,30,1); select test1.pid,test1.num,test2.sid,test2.num from test1,test2 where test1.pid=test2.pid; 这样子吗?
不是哦
ferryman_mail 2015-12-15
  • 打赏
  • 举报
回复
select * from test2 t2 left join test1 t1 on t2.pid=t1.pid 这样就行了。连接后 t1想要0的话 isnull 函数就好了。
a346322359 2015-12-14
  • 打赏
  • 举报
回复
create table test1(pid int, num int); insert into test1 values (1,30); create table test2(sid int, num int,pid int); insert into test2 values (2,10,1),(3,30,1); select test1.pid,test1.num,test2.sid,test2.num from test1,test2 where test1.pid=test2.pid; 这样子吗?

56,687

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧