我建了三张表进行连接操作 但是得不出想要的结果,请高手们帮帮忙
第一个表tb_level
LevelId LevelName
1 轻
2 中
3 重
第二张表tb_Danger
DangerId UserId LeveLId
1 4 1
2 4 2
3 4 3
4 2 1
5 2 1
6 2 2
7 2 2
8 5 3
9 2 3
10 3 1
11 3 1
12 3 1
13 3 2
14 3 2
15 3 2
16 3 3
17 3 3
18 3 3
s
第三张表bt_User
UserId UserName
2 y
3 z
4 c
5 q
这是我的sql语句
SELECT LevelName '程度',UserName '姓名',COUNT(LevelName) as '次数'
FROM tb_Danger
LEFT JOIN tb_Level ON tb_Danger.LevelId = tb_Level.LevelId
LEFT JOIN tb_Users ON tb_Danger.UserId = tb_Users.UserId --AND Limit = 1
GROUP BY LevelName,UserName order by LevelName desc
运行出来后y,z,c的“程度”都有“轻”,“中”,“重”三个而q只有一个“重”的程度,其他两个没值不显示,怎样写sql语使q的“轻”,“中”像y,z,c一样显示(没值以0显示)
------解决方案--------------------
- SQL code
这样的效果?你把表对应名称换成你的那个就成了..CREATE TABLE TB1(LevelId INT,NAME VARCHAR(4))INSERT INTO TB1(LevelId,NAME)SELECT 1,'轻'UNION ALLSELECT 2,'中'UNION ALLSELECT 3,'重'CREATE TABLE TB2(DangerId INT,UserId INT,LeveLId INT)INSERT INTO TB2(DangerId,UserId,LeveLId)SELECT 1,4,1UNION ALLSELECT 2,4,2UNION ALLSELECT 3,4,3UNION ALLSELECT 4,2,1UNION ALLSELECT 5,2,1UNION ALLSELECT 6,2,2UNION ALLSELECT 7,2,2UNION ALLSELECT 8,5,3UNION ALLSELECT 9,2,3UNION ALLSELECT 10,3,1CREATE TABLE TB3(UserId INT,UserName VARCHAR(4))INSERT INTO TB3(UserId,UserName) SELECT 2,'y'UNION ALLSELECT 3,'z'UNION ALLSELECT 4,'c'SELECT 5,'q' -------- SELECT * FROM TB1 SELECT * FROM TB2 SELECT * from TB3----查询;WITHDD AS(SELECT B.DangerId,A.UserName,B.LeveLIdFROM TB3 A LEFT JOIN TB2 BON A.UserId=B.UserId)SELECT B.*,A.NAMEFROM TB1 A LEFT JOIN DD BON A.LeveLId=B.LeveLId-------DangerId UserName LeveLId NAME----------- -------- ----------- ----1 c 1 轻4 y 1 轻5 y 1 轻10 z 1 轻2 c 2 中6 y 2 中7 y 2 中3 c 3 重9 y 3 重(9 行受影响)
------解决方案--------------------
- SQL code
少了个UNION ALL:SELECT 4,'c'SELECT 5,'q'换成:SELECT 4,'c'UNION ALLSELECT 5,'q'q没插入进去DangerId UserName LeveLId NAME----------- -------- ----------- ----1 c 1 轻4 y 1 轻5 y 1 轻10 z 1 轻2 c 2 中6 y 2 中7 y 2 中3 c 3 重8 q 3 重9 y 3 重(10 行受影响)
------解决方案--------------------
- SQL code
SELECT isnull(LevelName,'') '程度',isnull(UserName,'') '姓名',isnull(COUNT(LevelName),'') as '次数'FROM tb_DangerLEFT JOIN tb_Level ON tb_Danger.LevelId = tb_Level.LevelIdFULL JOIN tb_Users ON tb_Danger.UserId = tb_Users.UserId --AND Limit = 1GROUP BY LevelName,UserName order by LevelName desc