1

我有 4 个不同的表,它们为用户存储不同的事务,我想为某些特定用户合并所有事务。但问题是,所有这 4 个表都有大量数据,因此当我尝试将它们全部合并并与用户连接时,需要花费数小时来计算。我正在做的是:

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 次。

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

谢谢 !

4

3 回答 3

2

使用公用表表达式从您的用户中选择“ user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey' ”,或者选择临时表。

然后在您的联合中使用该结果。

于 2013-10-25T11:09:40.750 回答
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');
于 2013-10-25T11:14:48.087 回答
0

检查是否所有带有条件的字段都已被索引。(t.user_id, users: state,friends,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)
于 2013-10-25T11:19:42.533 回答