我正在学习加入并拥有以下表格。
学生
| ID | NAME |
-------------
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
通
| ID | MARKS |
--------------
| 2 | 80 |
| 3 | 75 |
故障
| ID | MARKS |
--------------
| 1 | 25 |
| 4 | 20 |
我想要的输出是:
| NAME | MARKS |
----------------
| B | 80 |
| C | 75 |
| A | 25 |
| D | 20 |
我写了一个这样的查询:
select s.id,s.name,p.marks from student s
left join pass p on s.id=p.id
left join (select f.marks,f.id from fail f ) as nn on s.id=nn.id
order by marks desc;
我得到的输出是:
| id | name | Marks|
--------------------
| 1 | B | 80 |
| 2 | C | 75 |
| 3 | A | Null |
| 4 | D | NUll |
无法弄清楚为什么Null会来。有什么指针吗?
答案 0 :(得分:0)
尝试以下查询,使用 COALESCE
select s.id,s.name,COALESCE(p.marks , nn.marks) as marks
from student s
left join pass p on s.id=p.id
left join fail nn on s.id=nn.id
order by marks desc;
<强> SQL Fiddle 强>
答案 1 :(得分:0)
您只选择传递的标记,这就是在falied结果附近出现null-s的原因。
如果要选择失败的标记,可以使用IF
条件
select s.id,s.name,IF(p.marks = null, nn.marks, p.marks) as markss
from student s
left join pass p on s.id=p.id
left join fail nn on s.id=nn.id
order by markss desc;
或者您可以使用union
传递和失败的结果。
select s.id,s.name, u.marks
from student s
left join ( (SELECT * FROM pass) UNION (SELECT * FROM fail) ) as n ON n.id = s.id
order by marks desc;
答案 2 :(得分:0)
您可以使用CASE
语句:
SELECT Name,
CASE WHEN P.Marks IS NULL THEN f.Marks ELSE P.Marks END AS Marks
FROM Student s
LEFT JOIN Pass p ON s.ID = p.ID
LEFT JOIN Fail f ON s.ID = f.ID
ORDER BY Marks DESC;
或者您也可以使用IF
声明:
SELECT Name,
IF(P.Marks IS NULL, F.Marks, P.Marks) AS Marks
FROM Student s
LEFT JOIN Pass p ON s.ID = p.ID
LEFT JOIN Fail f ON s.ID = f.ID
ORDER BY Marks DESC;
输出
| NAME | MARKS |
----------------
| B | 80 |
| C | 75 |
| A | 25 |
| D | 20 |
要了解有关JOIN的详情,请参阅:A Visual Explanation of SQL Joins
答案 3 :(得分:0)
您需要了解不同联接的工作原理,以了解您为NULL
列收到marks
的原因。
看看这里:A Visual Explanation of SQL Joins
您的相关示例是:
LEFT OUTER JOIN:
SELECT * FROM TableA
LEFT OUTER JOIN TableB
ON TableA.name = TableB.name
id name id name
-- ---- -- ----
1 Pirate 2 Pirate
2 Monkey null null
3 Ninja 4 Ninja
4 Spaghetti null null
marks
列的空值是左连接表中没有匹配的行。 您的示例的具体内容:
select s.id,s.name,p.marks
from student s
left join pass p on s.id=p.id
left join (select f.marks,f.id from fail f ) as nn on s.id=nn.id
order by marks desc;
The output i got is this:
id | name | Marks
-------------------
1 | B | 80
2 | C | 75
3 | A | Null
4 | D | NUll
这将返回所有学生行。