SQL语句中的大小写或

时间:2018-07-12 03:33:44

标签: sql

带有course_article,gr_article和user_score的表。

  

该课程可以在课程中包含许多文章:7可以包含文章1,2,5,6,7。

     

只有很少的文章被评分:1,6和2,5,7没有被评分。

     

用户尝试所有文章:只能从gr_article获得分级的文章1,6,从course_article获得2,5,7。

我希望所有课程,包括文章和用户评分的表格都在一张表中,如输出所示。

SELECT u.userid ,
       c.cid ,
       a.id ,
       u.score ,
       ( CASE WHEN c.cid = a.cid THEN u.score
              ELSE 0
         END ) AS "score"
FROM   course_article c
       JOIN gr_article a ON c.cid = a.cid
       JOIN user_score u ON u.a_id = a.id
WHERE  u.userid = 8
       AND c.cid = 7;

当我执行查询时,它仅显示用户尝试的评分文章,但我需要显示所有课程文章。

表格

course_article
+--------------+
|   id  cid    |
+--------------+
|     1    7   |
|     2    7   |
|     3    5   |
|     4    5   |
|     5    7   |
|     6    7   |
|     7    7   |
+--------------+

gr_article
+------------------------+
| id  cid  article_name  |
+------------------------+
| 1    7       A1        |
| 2    7       A4        |
| 3    7       A5        |
| 4    7       A3        |
| 5    7       A2        |
| 6    7       A44       |
| 7    7       A6        |
+------------------------+

user_score
+------------------------------+
|   id  a_id  userid   score   |
+------------------------------+
|     1    2      8       3.4  |
|     2    3      3       2.0  |
|     3    4      8       6.7  |
|     4    5      3       4.5  |
|     5    1      8       5.6  |
+------------------------------+

输出

+-----------------------------+
|  userid cid  a_id   score   |
+-----------------------------+
|       8     7    2      3.4 |
|       8     7    4      6.7 |
|       8     7    1      5.6 |
|       8     7    5       0  |
|       8     7    6       0  |
|       8     7    7       0  |
+-----------------------------+

1 个答案:

答案 0 :(得分:1)

您需要首先确定用户应该为哪些课程评分,然后执行OUTER JOIN,以便为尚未评分的文章显示0.0

假设没有与usercourse相关的表,或者如果用户在课程中获得了至少1个等级的评分,则可以通过假设用户与课程相关来推断这种关系。当然。

然后,您会收到类似以下的查询:

SELECT
    uc.userid,
    a.cid,
    a.id AS a_id,
    COALESCE(us.score, 0) AS score -- If no user score, assume 0
FROM (
    SELECT DISTINCT
        us.userid,
        a.cid
    FROM user_score us
        INNER JOIN gr_article a
            ON us.a_id = a.id
    ) uc -- Get user/course relationship
    INNER JOIN gr_article a
        ON uc.cid = a.cid -- Get all possible articles for user courses
    INNER JOIN course_article ca
        ON uc.cid = ca.cid -- Join back to course article as requested (not sure exactly of conditions you may need)
    LEFT OUTER JOIN user_score us -- Get available scores by article for user
        ON us.userid = uc.userid
            AND us.a_id = a.id
 WHERE uc.userid = 8 -- Here is sample filter by user id

已更新,以显示如何按用户ID进行过滤

如果要按用户ID进行过滤,则它必须是uc.userid而不是us.userid-否则会使OUTER JOIN变成INNER JOIN。我更新了查询以显示用户ID过滤器示例。

这是一个带有用户ID过滤器的SQL Fiddle: http://sqlfiddle.com/#!18/a1b8d/12/0