MySql从多个select中选择一行

时间:2015-05-16 23:36:11

标签: mysql sql

我无法弄清楚如何从表中获取一行:

我在一个范围/条件中搜索,我需要7列:最高价格,最低价格,最后价格,(如果价格> = x,那么第一个价格> = x及其时间) ,(如果和当价格< = y)。

表格是:

id (int, key unique)
date (varchar, don't need it) 
price (decimal) 
unix (int, key) (unix time)
ck (int, key)
fk (int, key)

我尝试了多个选择/加入,但是如果只有一个选择是空的(也许如果Price赢了> = x)它会返回整个空,我还是需要一个结果...

SELECT *  FROM 
    (SELECT date , price as 'Sprc', unix as 'Sunx' 
    FROM prices WHERE
        (unix BETWEEN 1420185600 AND 1420192800) AND
        ck>0 AND fk=0 AND 
        price <= 1000 
    order by unix ASC limit 1) as tmp1
JOIN
    (SELECT date , price as 'TPprc', unix as 'TPunx'  
    FROM prices WHERE  
        (unix BETWEEN 1420185600 AND 1420192800) AND  
        ck>0 AND 
        fk=0 AND 
        price >= 100 
    order by unix ASC limit 1) as tmp2
JOIN
    (SELECT MIN(price) as 'min', MAX(price) as 'max'  
    FROM prices WHERE 
        ck>0 AND 
        fk=0 AND  
        (unix BETWEEN 1420185600 AND 1420192800) 
    order by unix ASC limit 1)  as tmp3
JOIN
    (SELECT date, price as 'last'  
    FROM prices WHERE 
        ck>0 AND 
        fk=0 AND 
        (unix BETWEEN 1420185600 AND 1420192800) 
    order by unix DESC limit 1)  as tmp4;

1 个答案:

答案 0 :(得分:0)

将单词LEFT放在每个联接语句的前面。

这样做表示查询应返回第一个表中的所有行,无论它是否在第二个表中找到匹配的行。