将多个选择与更新结合使用

时间:2015-01-01 20:47:55

标签: mysql join sql-update subquery

我有一个拖动我的应用程序的查询。必须有一种方法可以通过将更新与选择结合来改进这一点。任何帮助赞赏。这是一个非常慢的查询:

Select t1.id, t2.tracker from Table1 t1, Table2 t2 where t1.id=t2.id and t2.tracker is not null

以上返回我可以处理的行集。对于返回的每一行,我检查a中的跟踪器 第三个表,看看是否只存在一行:

select tracker from Table3 where tracker="from above query". 

如果表3中跟踪器的计数为1行,则我会在表1中执行更新。

Update Table 1, set some field where id=t1.id

我如何结合这个?列出的答案很精彩,但我想这个问题还不够明确。因此,我编辑了这个问题。

表1返回了要更新的ID的可能列表。 表2返回了我需要搜索表3的跟踪器。 表3告诉我跟踪器是否只存在一次,所以我可以用它来回到表1和 更新它。

1 个答案:

答案 0 :(得分:0)

通过使用HAVING子句和其他LEFT JOIN,您可以将前两个查询合并为一个tracker仅针对Table3中包含一条记录的查询像HAVING COUNT(t3.tracker) = 1

这样的表达式

SELECT部分如下:

SELECT
  t1.id,
  t2.tracker
FROM 
  -- Your original comma-separated FROM clause (implicit inner join)
  -- has been replaced with a more modern explicit INNER JOIN, which
  -- works more clearly with the LEFT JOIN we need to do.
  Table1 t1
  INNER JOIN Table2 t2 ON t1.id = t2.id
  -- left join table 3 by tracker value
  LEFT JOIN Table3 t3 ON t2.tracker = t3.tracker
WHERE t2.tracker IS NOT NULL
GROUP BY
  t1.id,
  t2.tracker
-- limit the group to only those with 1 tracker in t3
HAVING COUNT(t3.tracker) = 1

现在,您能够将其填充到UPDATE JOIN查询中。 MySQL的update-join语法如下所示:

UPDATE 
  Table1 t_up
  -- join Table1 in its normal form against the query from above
  -- MySQL won't allow an IN () subquery for update in most versions
  -- so it has to be done as a join instead.
  JOIN (
    -- the subquery only needs to return t1.id
    SELECT t1.id
    FROM 
      Table1 t1
      INNER JOIN Table2 t2 ON t1.id = t2.id
      LEFT JOIN Table3 t3 ON t2.tracker = t3.tracker
    -- Filter to those with non-null t2.tracker
    WHERE t2.tracker IS NOT NULL
    GROUP BY
      -- Since only id was in SELECT, only id needs to be in GROUP BY
      t1.id
    HAVING COUNT(t3.tracker) = 1
  ) t_set ON t_up.id = t_set.id
SET t_up.some_field = 'SOME NEW VALUE'

Here is a demonstration of the concept in action...