简体   繁体   English

MYSQL - 子查询问题 - 不能重用表

[英]MYSQL - Subqueries problem - Cant reuse the table

WITH t as (
SELECT *
            FROM scd p
            WHERE  p.modified_date > FROM_UNIXTIME(1593060230)
                AND ( p.main_id = 1
                OR FIND_IN_SET(1, p.mult_ids) <> 0 )
            ORDER BY modified_date DESC
            LIMIT 2 OFFSET 0
),
del as (
SELECT 
* 
FROM t WHERE (status <> 1 AND status <> 2)
),
w_del as (
SELECT 
* 
FROM t WHERE (status = 1 OR status = 2)
)
SELECT w_del.*, del.* FROM w_del,del;

How do I achieve this with normal sub queries.我如何通过普通的子查询来实现这一点。 I am using MySQL 5.7 and can't use CTEs.我正在使用 MySQL 5.7 并且不能使用 CTE。 Im getting can't reuse table error if I use UNION/sub-queries.如果我使用 UNION/子查询,我将无法重用表错误。 Is there a way to achieve this without temporary tables?有没有办法在没有临时表的情况下实现这一点?

Please help.请帮忙。

You can just plug in the code for each alias.您可以为每个别名插入代码。 . . . . and keep doing that until you are at the base tables:并继续这样做,直到你在基表:

SELECT w_del.*, del.*
FROM (SELECT t.*
      FROM (SELECT *
            FROM scd p
            WHERE p.modified_date > FROM_UNIXTIME(1593060230) AND
                  ( p.main_id = 1 OR FIND_IN_SET(1, p.mult_ids) <> 0 )
            ORDER BY modified_date DESC
            LIMIT 2 OFFSET 0
           ) t
       WHERE (status <> 1 AND status <> 2)
      ) w_del CROSS JOIN
     (SELECT t.*
      FROM (SELECT *
            FROM scd p
            WHERE p.modified_date > FROM_UNIXTIME(1593060230) AND
                  ( p.main_id = 1 OR FIND_IN_SET(1, p.mult_ids) <> 0 )
            ORDER BY modified_date DESC
            LIMIT 2 OFFSET 0
           ) t
       WHERE (status = 1 OR status = 2)
      ) del;

One critical point, though: The definition of t is using ORDER BY and LIMIT .不过,一个关键点是: t的定义是使用ORDER BYLIMIT If there are ties in the modified_date column, then the two subqueries could return different result sets.如果modified_date列中存在关联,则两个子查询可能返回不同的结果集。 You have two choices to avoid a problem here:您有两种选择可以避免此处出现问题:

  1. Add additional keys to the ORDER BY to ensure that the sorting is stable (ie returns the same results each time because the combination of keys is unique).ORDER BY添加额外的键以确保排序稳定(即每次返回相同的结果,因为键的组合是唯一的)。
  2. Materialize the subquery using a temporary table.使用临时表实现子查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM