怎么样实现这样一个显示,一对多的关系

MySql 码拜 8年前 (2016-02-15) 779次浏览
表 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
即父表和子表联合起来,但是父表仅需显示一行,子表全部显示。
解决方案

20

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;
这样子吗?

20

select * from test2 t2
left join test1 t1 on t2.pid=t1.pid
这样就行了。连接后 t1想要0的话 isnull 函数就好了。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么样实现这样一个显示,一对多的关系
喜欢 (0)
[1034331897@qq.com]
分享 (0)