MySql将更新与内部联接和限制相结合

时间:2014-09-11 06:06:20

标签: mysql sql

我正在尝试使用amga加入的表amgb中的一行更新表itemTempId中的一行。

我的问题是,amgbitemTempId中最多可能有6行,我只需要使用其中一行进行更新。

我熟悉使用连接进行更新,但是当我添加一个Limit(以便只获得一行)时,我收到错误消息Incorrect usage of update and limit。我读到这是不可能的,但还有另一种方法吗?

阿姆加

"id"    "itemId"    "itemTempId"    "itemImageName" "itemName"                  "itemCountry"   "userId"
"1"     "US1"       "T001"          \N              "Samsung Galaxy Note 5"     "US"            "1"
"2"     "CA2"       "T002"          \N              "Samsung Galaxy Note 6"     "CA"            "2"
"3"     "UK3"       "T003"          \N              "Samsung Galaxy Note 7"     "UK"            "3"

amgb

"id"    "itemId"    "itemTempId"    "itemImageName"     "userId"
"1"     "US1"       "T001"          "front.jpg"         "1"
"2"     "US1"       "T001"          "side-left.jpg"     "1"
"3"     "US1"       "T001"          "side-right.jpg"    "1"
"4"     "US1"       "T001"          "back.jpg"          "1"
"5"     "CA2"       "T002"          "front.jpg"         "2"
"6"     "CA2"       "T002"          "side-left.jpg"     "2"
"7"     "CA2"       "T002"          "side-right.jpg"    "2"
"8"     "CA2"       "T002"          "back.jpg"          "2"
"9"     "UK3"       "T003"          "front.jpg"         "3" 

我用的是

update amga a inner join amgb b on a.itemTempId = b.itemTempId 
set a.itemImageName = b.itemImageName where a.itemTempId = 'T001' limit 1;

预期结果:更新后的表格amga

 "id"   "itemId"    "itemTempId"    "itemImageName" "itemName"                  "itemCountry"   "userId"
    "1"     "US1"       "T001"      front.jpg       "Samsung Galaxy Note 5"     "US"            "1"
    "2"     "CA2"       "T002"      \N              "Samsung Galaxy Note 6"     "CA"            "2"
    "3"     "UK3"       "T003"      \N              "Samsung Galaxy Note 7"     "UK"            "3"

注意:itemTempId已更新为front.jpg,这是itemTempId = T001

amgb的第一行

任何帮助表示感谢。

更新 我注意到,如果我删除限制,它也会有效。但这是正确的方法吗? MySql对select中的其他行做了什么?

update amga a inner join amgb b on a.itemTempId = b.itemTempId 
set a.itemImageName = b.itemImageName where a.itemTempId = 'T001';

1 个答案:

答案 0 :(得分:1)

也许你可以使用子查询:

UPDATE amga a
SET a.itemImageName =
  (SELECT b.itemImageName
   FROM amgb b
   WHERE b.itemTempId = 'T001'
   ORDER BY b.id LIMIT 1)
WHERE a.itemTempId = 'T001'