SQL:子查询?使用条件拉柱

时间:2016-04-06 02:15:24

标签: mysql sql

当前的SQL代码是:

    SELECT k.id, k.symbol, y.close, y.volume, 
((y.close / y.close_adj_previous_day)-1) AS percent_change
        FROM symbols k
        JOIN stocks y ON k.id = y.id
    WHERE 
        k.t_removed = 0
        AND t = '$max_t'
    ORDER BY percent_change DESC
    LIMIT 10

尝试获取close_adj_previous_day。目前我使用另一个查询来获取close_adj_previous日:

        SELECT k.close_adj AS close_adj_previous_day
        FROM stocks k
        WHERE 
            k.id = '$id'
            AND k.t = '$max_t_minus_one'
        LIMIT 1

如何组合这些查询,以便将结果排序为最高查询?谢谢你们/ gals。

表中的半个例子:

Example Table Kind Of

1 个答案:

答案 0 :(得分:1)

如果您有变量,请使用join: 您在变量中有前一天的值。您可以使用join

SELECT k.id, k.symbol, y.close, y.volume, 
   ((y.close / yprev.close)-1) AS percent_change,
   yprev.close_adj AS close_adj_previous_day
FROM symbols k JOIN
     stocks y
     ON k.id = y.id AND y.t = '$max_t' JOIN
     stocks yprev
     ON k.id = yprev.id and yprev.t = '$max_t_minus_one'
WHERE k.t_removed = 0
ORDER BY percent_change DESC
LIMIT 10