我有一个mysql查询,如果user_name
表中存在sess_start
,则从sess_active
表返回user_name
和sess_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)