MySQL如何使此子查询正确运行?

时间:2012-03-01 01:49:49

标签: mysql join subquery dml

我有以下数据库表:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

可以通过连接实现

SELECT people.f_name, IF(results.grade <> 0, results.grade, 'N/A') from people
JOIN results USING(f_id)

答案 2 :(得分: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