MySQL根据select

时间:2017-05-19 08:57:26

标签: mysql sql mariadb

我有一个名为downloads的表格,其中包含从各种网址下载的文件记录。有一列downloads.createdDATETIME和列downloads.master,它是一个布尔字段,用于说明哪个记录是主副本。

以下查询成功获取具有最新日期的记录:

SELECT t1.master
FROM downloads t1
WHERE t1.id = (SELECT t2.id
             FROM downloads t2
             WHERE t2.url_id = t1.url_id            
             ORDER BY t2.created DESC
             LIMIT 1)

我想通过将master设置为1来更新这些记录。

我要执行的SELECTUPDATE都适用于相同的表格downloads

我尝试了以下MySQL - UPDATE query based on SELECT Query

UPDATE downloads 
(
    SELECT t1.master
    FROM downloads t1
    WHERE t1.id = (SELECT t2.id
             FROM downloads t2
             WHERE t2.url_id = t1.url_id            
             ORDER BY t2.created DESC
             LIMIT 1)
 )
 SET master = 1

但这会产生错误:

Error : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '( SELECT t1.master FROM downloads t1 WHERE t1.id = (SELECT t2.id ' at line 2

我在上面的链接上尝试的其他解决方案更新了整个表格,因为我只是尝试更新从我工作的SELECT中检索到的记录。请有人帮我指点正确的方向吗?

3 个答案:

答案 0 :(得分:1)

使用加入

update t1 SET t1.master = 1  from downloads as  t1 
join downloads as  t2 
on t2.url_id = t1.url_id 
ORDER BY t2.created DESC LIMIT 1

答案 1 :(得分:1)

你需要一起使用join和update来做这样的事情。尝试

  UPDATE downloads d
  JOIN (SELECT t1.id FROM downloads t1 
        WHERE t1.id = (SELECT t2.id
                       FROM downloads t2
                       WHERE t2.url_id = t1.url_id            
                       ORDER BY t2.created DESC LIMIT 1
                       ) 
        ) a on d.id = a.id  SET d.`master` = 1

这应该有用,也许你可以更多地优化你提取最新记录的方法

答案 2 :(得分:0)

试试这个

   UPDATE downloads 
    SET master = 1
    FROM
    (
        SELECT t1.master
        FROM downloads t1
        WHERE t1.id = (SELECT t2.id
                 FROM downloads t2
                 WHERE t2.url_id = t1.url_id            
                 ORDER BY t2.created DESC
                 LIMIT 1)
     )