SQL查询添加与子查询相关的位置

时间:2016-12-09 16:55:52

标签: mysql sql subquery where

尝试在子查询结果上获取where语句。除了 AND low_36!= NULL 之外,下面的工作正如我所希望的那样。我需要这个来停止low_36的输出为NULL的结果。

SELECT offers.*, 
(SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 23 ) AS low_24, 
(SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 35 ) AS low_36
(SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 47 ) AS low_48 
FROM offers 
LEFT JOIN m_v ON v_v.code = offers.code 
LEFT JOIN m_f_t ON v.f_t_id = m_f_t.id 
LEFT JOIN m_t_t ON v.t_t_id = m_t_t.id 
WHERE status = 1 
AND low_36 != NULL 
LIMIT 2 OFFSET 0

我知道你不能在main where语句中使用子查询的结果,但这是我得到的最接近正确结果的结果。感谢您的任何反馈

2 个答案:

答案 0 :(得分:0)

快捷方式

SELECT *
FROM
    (SELECT offers.*, 
    (SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 23 ) AS low_24, 
    (SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 35 ) AS low_36
    (SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 47 ) AS low_48 
    FROM offers 
    LEFT JOIN m_v ON v_v.code = offers.code 
    LEFT JOIN m_f_t ON v.f_t_id = m_f_t.id 
    LEFT JOIN m_t_t ON v.t_t_id = m_t_t.id 
    WHERE status = 1) a
WHERE low_36 IS NOT NULL 
LIMIT 2 OFFSET 0

答案 1 :(得分:0)

我怀疑你想在子查询本身中排除空值,从而避免使你的聚合值无效。试试这个:

SELECT offers.*, 
(SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 23 ) AS low_24, 
(SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 35 and price is not null) AS low_36,
(SELECT ROUND( MIN( price ) ,2) FROM o_prices WHERE o_id = offers.id AND months = 47 ) AS low_48 
FROM offers 
LEFT JOIN m_v ON m_v.code = offers.code 
LEFT JOIN m_f_t ON m_v.f_t_id = m_f_t.id 
LEFT JOIN m_t_t ON m_f_t.t_t_id = m_t_t.id 
WHERE status = 1 
LIMIT 2 OFFSET 0