一个表里有多个字段需要同时使用字典表进行关联显示,如何写sql查询语句

时间:2022-06-29 06:19:13

参考:https://bbs.csdn.net/topics/330032307

数据库里面有一个字典表,这张表里面有id段和对应的名字字段。
在另外一个记录的表里面有对应的上述字典表的id,而且有多个字段都含有该id字段。需要将其查出来,并且用名字。

1、第一种写法,不使用 left join

SELECT a.id AS '编号', 'STORY' AS '类型' , a.title AS '标题',b.name AS '所属项目'  ,
c.realname AS '创建者',
a.estimate AS '计划时间',
d.realname AS '责任研发',
a.resolvedDate AS '实际解决时间',a.closedDate AS '实际关闭时间',a.STATUS
FROM zt_story a , zt_project b, zt_user c, zt_user d
WHERE a.project=b.id AND a.openedby=c.account AND a.assignedTo=d.account AND a.id>=8650 AND a.id<= 8692
ORDER BY a.id

查询出的结果是严格的比照,为35条,比期望的43条少了8条。因为字典表内容缺少一些。

SELECT a.id AS '编号', 'BUG' AS '类型' , a.title AS '标题',b.name AS '所属项目' ,
c.realname AS '创建者',
a.estimateDoneDate AS '计划时间',
d.realname AS '责任研发',
a.resolvedDate AS '实际解决时间',a.closedDate AS '实际关闭时间',a.STATUS
FROM zt_bug a , zt_project b, zt_user c, zt_user d
WHERE a.project=b.id AND a.openedby=c.account AND a.assignedTo=d.account AND a.id>=28095
ORDER BY a.id

查出29条记录。

2、使用Left join方法,可以全部查出来,43条,一些字典表里没有的数据对应字段为空

SELECT a.id AS '编号', 'STORY' AS '类型' , a.title AS '标题',b.name AS '所属项目'  ,
c.realname AS '创建者',
a.estimate AS '计划时间',
d.realname AS '责任研发',
a.resolvedDate AS '实际解决时间',a.closedDate AS '实际关闭时间',a.STATUS
FROM zt_story a
LEFT JOIN zt_project b ON a.project=b.id
LEFT JOIN zt_user c ON a.openedby=c.account
LEFT JOIN zt_user d ON a.assignedTo=d.account
WHERE a.id>=8650 AND a.id<= 8692
ORDER BY a.id

上述语句完全将期望的43条记录全部查出,只是有8条记录的部分字段是空的。

SELECT a.id AS '编号', 'BUG' AS '类型' , a.title AS '标题',b.name AS '所属项目' ,
c.realname AS '创建者',
a.estimateDoneDate AS '计划时间',
d.realname AS '责任研发',
a.resolvedDate AS '实际解决时间',a.closedDate AS '实际关闭时间',a.STATUS
FROM zt_bug a
LEFT JOIN zt_project b ON a.project=b.id
LEFT JOIN zt_user c ON a.openedby=c.account
LEFT JOIN zt_user d ON a.assignedTo=d.account
WHERE a.id>=28095
ORDER BY a.id

该表对应的字典表数据均存在,所以上述语句执行后查询到的结果也是29条。

做个标记。

总结:

根据自己的期望,如果需要严格比照,不要用 LEFT JOIN。

如果需要显示全部记录,使用 LEFT JOIN

https://blog.csdn.net/flexitime/article/details/2380531
Delphi中写复杂SQL语句的简便方式