将2个select语句重写为一个JOIN语句

时间:2017-05-26 09:16:27

标签: mysql join

我一直在接受一个我无法弄清楚的JOIN声明。

我想在两个不同的表中获取最新(最新)的条目,并将结果连接到输出中。

2个Select语句看起来像这样,它们按预期工作但当我尝试将它们作为JOIN语句重写时,我似乎无法得到正确的结果。

请帮助,谢谢。

SELECT MaxNum 
FROM table1 
WHERE UserID = 4
ORDER BY Date DESC
LIMIT 1

SELECT MinNum 
FROM table2 
WHERE UserID = 4
ORDER BY Date DESC
LIMIT 1

4 个答案:

答案 0 :(得分:1)

我不确定连接在这里是否有意义。但是,您可以稍微修改一下您当前的查询内容:

xaxis

答案 1 :(得分:0)

由于每个查询只返回一行,您可以使用的一个脏技巧是cross join结果:

SELECT MaxNum, MinNum
FROM   (SELECT   MaxNum 
        FROM     table1 
        WHERE    UserID = 4
        ORDER BY Date DESC
        LIMIT    1) t 
CROSS JOIN (SELECT   MinNum 
            FROM     table2 
            WHERE    UserID = 4
            ORDER BY Date DESC
            LIMIT    1) s

答案 2 :(得分:0)

如果要将结果显示为一行,请将查询用作FROM子句中的子查询。

SELECT *
FROM 
  (SELECT MaxNum FROM table1 WHERE UserID = 4 ORDER BY `Date` DESC LIMIT 1) AS q1,
  (SELECT MinNum FROM table2 WHERE UserID = 4 ORDER BY `Date` DESC LIMIT 1) AS q2;

答案 3 :(得分:0)

select TOP 1 table1.MaxNum, table2.MinNum 
FROM table1 INNER JOIN table2 
ON table1.UserID = table2.UserID 
WHERE table1.UserID = 4 
ORDER BY table1.Date DESC