2013-02-19 28 views
5

在這個查詢我想更新那些記錄是最新posted.But我的這個查詢不工作請幫我什麼原因?爲什麼更新和選擇兩個不工作在同一個表

錯誤: - 您不能指定目標表 'beevers_products' 的更新在FROM子句

update beevers_products set product_name='my_product_name' where posted_date in (SELECT posted_date FROM `beevers_products` order by posted_date asc limit 1) 
+0

在MySQL中,你不能修改您在SELECT部分​​使用相同的表。檢查這個鏈接。 http://stackoverflow.com/questions/45494/mysql-error-1093-cant-specify-target-table-for-update-in-from-clause – cartina 2013-02-19 10:11:29

+0

你能解釋一下你想做什麼嗎?這個查詢似乎是inlogical bit – Shaolin 2013-02-19 10:13:23

回答

0

試試這個:

update beevers_products as t1, 
(select posted_date from beevers_products order by posted_date asc limit 1) as t2 
set t1.product_name = 'my_product_name' 
where t1.posted_date in (t2.posted_date); 

你將不得不放棄別名到你想要的記錄,並在使用where子句。

+0

我wana更新product_name這是最近通過單個查詢添加這個查詢(SELECT posted_date FROM'beevers_products' order by posting_date asc limit 1)給了我最新添加的日期,現在我wana更新這個產品....這兩個查詢工作單獨罰款,但結合其不工作? – 2013-02-19 10:19:19

+0

這就是我所說的。當它們被單獨使用時它會正常工作,但是當它們一起使用時它將不起作用。這是不允許的。 – 2013-02-19 10:21:34

+0

我已經更新了我的答案。嘗試一下。我已經測試過它的工作。 – 2013-02-19 10:31:47

0

試試這個

UPDATE beevers_products 
SET product_name = 'my_product_name' 
OUTPUT DELETED.product_name 
WHERE posted_date in (SELECT posted_date 
         FROM `beevers_products` 
         order by posted_date asc 
         limit 1) 

瞭解更多關於output

入住這 - >Can I update/select from a table in one query?
可能是它可以幫助你

0
INSERT INTO beevers_products (id, product_name) 
SELECT id, 'my_product_name' 
FROM beevers_products 
ORDER BY posted_date ASC 
LIMIT 1 
ON DUPLICATE KEY UPDATE product_name = VALUES(product_name) 

有一次,我學會了用INSERT ... SELECT ... ON DUPLICATE這麼多的可能性浮出水面。我只是有點好奇,只要你想posted_data ASCposted_data DESC

1

檢查:

UPDATE beevers_products 
SET product_name = 'my_product_name' 
WHERE posted_date = (SELECT posted_date 
        FROM beevers_products 
        ORDER BY posted_date DESC limit 1) 
相關問題