【问题标题】:SQL - Join one subquery for multiple times within unionSQL - 在联合内多次加入一个子查询
【发布时间】:2013-10-25 11:05:32
【问题描述】:

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

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

谢谢!

【问题讨论】:

    标签: sql performance subquery union


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      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');
      

      【讨论】:

      • 但是每个事务表中的字段数总是不同的,因此我从每个不同的事务表中提取不同的字段
      【解决方案3】:

      检查是否所有带条件的字段都已被索引。 (t.user_id,用户:状态,朋友,位置) 也尝试使用这个:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-02
        • 2011-07-06
        • 2012-10-19
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        相关资源
        最近更新 更多