SQL - 在union中多次加入一个子查询

时间:2013-10-25 11:05:33

标签: sql performance subquery union

我有4个不同的表,为用户存储不同的事务,我想为某些特定用户联合所有事务。但问题是,所有这4个表都有大量数据,因此当我尝试UNION所有这些并与用户一起加入时,计算需要数小时。我正在做的是:

SELECT blablabla
FROM transactions1 t1
JOIN users ON (users.id = t1.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey')
UNION
SELECT blablabla
FROM transactions2 t2
JOIN users ON (users.id = t2.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey')
UNION
SELECT blablabla
FROM transactions3 t3
JOIN users ON (users.id = t3.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey')
UNION
SELECT blablabla
FROM transactions4 t4
JOIN users ON (users.id = t4.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey')
ORDER BY date DESC

问题是,我正在跑步 JOIN users ON (users.id = t1.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey')此过滤器通过将每个事务表与用户连接4次。

为了获得最佳实践并提高查询效率,我该如何改进查询?

谢谢!

3 个答案:

答案 0 :(得分:2)

使用Common Table Expression或临时表格从用户中选择“ user.state = 1 AND user.friends> 1 AND user.loc ='Turkey'

然后在你的联盟中使用该结果。

答案 1 :(得分:1)

您可以尝试这样的事情:

SELECT blablabla
FROM transactions1 t1, transactions2 t2,transactions3 t3,transactions4 t4
JOIN users ON (users.id = t1.user_id OR users.id = t2.user_id OR users.id = t3.user_id 
OR users.id = t4.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey');

答案 2 :(得分:0)

检查所有具有条件的字段是否为INDEXED。 (t.user_id,用户:州,朋友,loc) 也尝试使用它:

select blablabla from
(
  select * from user where user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey'
) U1
join transactions1 t1 on (U1.Id=t1.User_id)

UNION ALL

select blablabla from
(
  select * from user where user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey'
) U1
join transactions1 t2 on (U1.Id=t2.User_id)

UNION ALL

select blablabla from
(
  select * from user where user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey'
) U1
join transactions1 t3 on (U1.Id=t3.User_id)

UNION ALL

select blablabla from
(
  select * from user where user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey'
) U1
join transactions1 t4 on (U1.Id=t4.User_id)