在WHERE子句中选择查询结果

时间:2016-07-19 15:51:58

标签: mysql

您好我正在尝试创建一个WHERE子句,其中条件是前一个选择的id,例如:

     SELECT 
        ,P1.caseid
        ,(SELECT SUM(P1.amount) FROM table_s P1 WHERE P1.status = 4 AND P1.caseid = 20) 
        as variable
        FROM table_s P1 GROUP BY P1.caseid";

让我们说P1.caseid每次迭代都有

的值
20,
45,
20,

如何在此处插入此值作为WHERE子句的条件:WHERE P1.status = 4 AND P1.caseid = 20

而不是P1.caseid = 20,它必须等于数据库中每行的实际caseid

因此对于每一行都是:

WHERE P1.caseid = 20 
WHERE P1.caseid = 45 
WHERE P1.caseid = 35 

在这种情况下,数字与数据库内的caseid相同。

TABLE NAME:table_s

id | caseid | amount | status 
-- | ------------------------
 1 | 20     | 10     | 4
 2 | 45     | 10     | 4
 3 | 20     | 10     | 4

DB如下,结果应为:

1 ROW = caseid: 20 amount: 20 status 4
2 ROW = caseid: 45 amount: 10 status 4

$variable = 20
$variable = 10

1 个答案:

答案 0 :(得分:1)

我想我已经解决了你所问的问题......

这里重要的注意事项是在外部和内部查询中为表使用不同的别名。否则你会遇到严重的范围问题。 (如果同一实体的两个实例具有相同的名称,MySQL怎么知道你指的是哪一个?它会选择最近范围内的那个。所以,相反,调用其中一个,例如,lookup。)

SELECT 
    P1.*,
    (
     SELECT SUM(lookup.amount)
       FROM table_s   lookup
      WHERE lookup.status = 4
        AND lookup.caseid = P1.caseid
    )
        correlated_sub_query_total_by_caseid
FROM
    table_s P1

但是这可以在没有相关子查询的情况下重写......

SELECT 
    P1.*,
    SUM(CASE WHEN status = 3 THEN amount END)   AS status_3_total,
    SUM(CASE WHEN status = 4 THEN amount END)   AS status_4_total
FROM
    table_s P1
INNER JOIN
    table_s lookup
        ON lookup.caseid = P1.caseid
GROUP BY
    P1.primary_key

那就是说,你添加了另一条评论似乎与你的问题有关......

the idea is to select the sum of the amount for each caseid and display it. as caseid - sum

为此你只需要聚合......

SELECT
    caseid,
    SUM(amount)
FROM
    table_s
GROUP BY
    caseid

如果您只想聚合状态为3或4的地方......

SELECT
    caseid,
    SUM(CASE WHEN status = 3 THEN amount ELSE 0 END)   status_3_total
    SUM(CASE WHEN status = 4 THEN amount ELSE 0 END)   status_4_total
FROM
    table_s
GROUP BY
    caseid