Mysql连接3个表输出

时间:2013-04-27 07:17:54

标签: mysql sql join

我正在学习加入并拥有以下表格。

学生

| 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会来。有什么指针吗?

4 个答案:

答案 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 |

See this SQLFiddle

要了解有关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

enter image description here

  • 您收到的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

这将返回所有学生行。

  • 有通过gtade的学生将显示成绩,而没有通过gtade的学生将显示为null。