MySQL-也从EXISTS(SELECT ..)语句中获取数据

时间:2019-06-01 07:16:02

标签: mysql

我有一个mysql查询,如果user_name表中存在sess_start,则从sess_active表返回user_namesess_active_tmp

下面针对上面的查询按原样工作,但是我也想从sess_active_tmp表中检索数据。由于我在SELECT部分执行了另一个EXISTS语句,因此我是否也应该能够检索该语句的数据?

工作查询:

SELECT sess_main.user_name, 
       sess_main.sess_start 
FROM   sess_active AS sess_main 
WHERE  ( sess_main.user_name = 'testuser' 
         AND sess_main.sess_stop IS NULL ) 
       AND EXISTS (SELECT user_name 
                   FROM   sess_active_tmp AS sess_temp 
                   WHERE  sess_temp.user_name = 'testuser' 
                          AND sess_temp.sess_start = 
                              sess_main.sess_start 
                          AND sess_temp.sess_stop IS NULL) 

查询我正在尝试使其工作;

SELECT sess_main.user_name, 
       sess_main.sess_start,
       sess_temp.upload_byte,
       sess_temp.download_byte,
FROM   sess_active AS sess_main 
WHERE  ( sess_main.user_name = 'testuser' 
         AND sess_main.sess_stop IS NULL ) 
       AND EXISTS (SELECT user_name 
                   FROM   sess_active_tmp AS sess_temp 
                   WHERE  sess_temp.user_name = 'testuser' 
                          AND sess_temp.sess_start = 
                              sess_main.sess_start 
                          AND sess_temp.sess_stop IS NULL) 

我还向sess_temp.upload_byte, sess_temp.download_byte select语句中添加了sess_temp,但它也不起作用。

是否只能使用JOIN才能实现,如果可以,则会降低性能吗?因为此查询每2分钟将运行2-3k次(用户)。

谢谢。

编辑:以下查询可以实现我想要实现的目标,但是我有性能方面的顾虑,这是实现我想要实现的最佳方法吗?

SELECT sess_main.user_name, 
       sess_main.sess_start, 
       sess_temp.upload_byte, 
       sess_temp.download, 
FROM   sess_active AS sess_main 
       INNER JOIN sess_active_tmp sess_temp 
               ON ( sess_temp.user_name = sess_main.user_name 
                    AND sess_temp.sess_start = sess_main.sess_start 
                    AND sess_temp.sess_stop IS NULL ) 
WHERE  ( sess_main.user_name = 'testuser' 
         AND sess_main.sess_stop IS NULL ) 
       AND EXISTS (SELECT user_name 
                   FROM   sess_active_tmp AS sess_temp 
                   WHERE  sess_temp.user_name = 'testuser' 
                          AND sess_temp.sess_start = sess_main.sess_start 
                          AND sess_temp.sess_stop IS NULL) 

0 个答案:

没有答案