MySQL同一列连接不同的行

时间:2018-10-30 04:06:49

标签: mysql

我有两个与项目相关的表,如下所示

表“ old_project”

+------------+----------+--------------+----------+
| project_no | project  |    amount    |  status  |
+------------+----------+--------------+----------+
|        001 | project1 |   75,000.00  | original |
|        002 | project2 |   32,000.00  | original |
|        003 | project3 |  150,000.00  | original |
|        004 | project4 |   25,000.00  | original |
|        005 | project5 |   45,000.00  | original |
|        006 | project6 |   80,000.00  | original |
+------------+----------+--------------+----------+

表“ new_project”

+----------------+------------+-----------+--------------+----------+
| old_project_no | project_no |  project  |    amount    |  status  |
+----------------+------------+-----------+--------------+----------+
|                |        001 | project1  |   75,000.00  | original |
|                |        002 | project2  |   32,000.00  | original |
|                |        003 | project3  |  150,000.00  | original |
|            001 |        004 | project4  |   50,000.00  | revised  |
|                |        005 | project5  |   45,000.00  | original |
|            003 |        006 | project6  |   70,000.00  | revised  |
+----------------+------------+-----------+--------------+----------+

02)如果一个项目在new_project_table中具有old_project_no且status =“ revised”,则应更改数量字段:

例如:- a)project_no 004的数量= old_project表中的project_no 001的数量-new_project表中的project_no 004的数量

b)project_no 006的数量= old_project表中的project_no 003的数量-new_project表中的project_no 006的数量

03)之后,通过连接两个表,所需的输出应如下所示:

+------------+-----------+--------------+----------+
| project_no |  project  |    amount    |  status  |
+------------+-----------+--------------+----------+
|        001 | project1  |   75,000.00  | original |
|        004 | project4  |   50,000.00  | revised  |
|        003 | project3  |  150,000.00  | original |
|        006 | project6  |   70,000.00  | revised  |
+------------+-----------+--------------+----------+

04)因此,我使用了以下查询

SELECT
    project_no,
    project,
    old_project.amount - new_project.amount,
    status
FROM
    new_project
JOIN
    old_project ON old_project.project.no = new_project.project.no
WHERE
    project_no IN (SELECT project_no
                   FROM new_project
                   WHERE status="revised") 

05)但未获得所需的输出。我不明白我要怎么做。谁能帮我吗?

1 个答案:

答案 0 :(得分:3)

  • 您只需要从Left Join表到new_project上的old_project表执行project_no
  • 现在,我们可以使用Case .. When表达式来有条件地评估金额值。
  • 如果存在对应的旧项目(旧项目金额Is Not Null),我们可以计算出差异;否则使用新的项目金额。

尝试以下查询:

SELECT
  np.project_no, 
  np.project, 
  CASE 
    WHEN op.amount IS NOT NULL THEN op.amount - np.amount 
    ELSE np.amount
  END AS amount, 
  np.status 
FROM new_project AS np 
LEFT JOIN old_project AS op ON op.old_project_no = np.project_no