0

我有以下数据库表:

People
+--------+------------+------------+-----------+
|  f_ID  |  F_NAME    |    STUFF   | F_VALUE   | 
+--------+------------+------------+-----------+
|    1   |   Zoe      |    blah    |     101   |
|    2   |   Jimy     |    derka   |     202   |
|    3   |   Kate     |    shazam  |     20    |
|    4   |   Sue      |    pow     |      2    |
+--------+------------+------------+-----------+

RESULTS
+------- ---+------------+
| F_ID      |   RESULTS  | 
+-----------+------------+
| 1         |     Good   |
| 4         |      OK    |
+-----------+------------+

如何创建查询以显示人员表中的所有条目,如下所示:

+------------+------------+
|   NAME     |    GRADE   | 
+------------+------------+
|   Zoe      |     Good   |
|   Jimy     |     N/A    |
|   Kate     |     N/A    |
|   Sue      |     OK     |
+------------+------------+

我试过这个查询,但它不能正常工作:

SELECT 
NAME
GRADE
(
SELECT 
p.F_NAME AS NAME,
r.RESULTS

FROM People p
JOIN RESULTS r ON r.F_ID=p.F_ID

UNION

SELECT 
p.F_NAME AS NAME,
"N/A"

FROM People p
JOIN RESULTS r ON r.F_ID=p.F_ID
)a
4

3 回答 3

2

您应该使用左连接。对于不存在记录的 GRADE,您将获得 NULL。呈现数据时,只需输入 N/A 而不是 null。

select People.F_NAME as NAME, RESULTS.RESULTS AS GRADE
from People left join RESULTS ON People.f_ID = RESULTS.f_ID

或者,如果您想要 N/A 而不是 null,请使用 IF

select People.F_NAME as NAME, IF(RESULTS.RESULTS is NULL, 'N/A', RESULTS.RESULTS) AS GRADE
from People left join RESULTS ON People.f_ID = RESULTS.f_ID

或使用 COALESCE(感谢@bfavaretto)

select People.F_NAME as NAME, COALESCE(RESULTS.RESULTS, 'N/A') AS GRADE
from People left join RESULTS ON People.f_ID = RESULTS.f_ID
于 2012-03-01T01:54:36.297 回答
1

可以通过加入来实现

SELECT people.f_name, IF(results.grade <> 0, results.grade, 'N/A') from people
JOIN results USING(f_id)
于 2012-03-01T01:55:45.360 回答
1

不使用UNION,您可以使用LEFT JOIN

SELECT  a.F_Name, 
        COALESCE(b.Results, 'N/A') Grade
FROM    People a LEFT JOIN Results b ON
            a.f_IF = b.F_ID
于 2012-03-01T02:17:50.563 回答