MySql仅使用单个选择查询更新表

时间:2015-01-29 16:24:20

标签: mysql

我使用table_b中的数据更新table_a,如下所示。

table_a

"id"    "addedUser" "addedName"
"1"     "1"         "james"
"2"     "1"         "kirk"
"3"     "1"         "lars"
"4"     "2"         "michael"

update table_b set 
totalFriends = 20, #data I supply
totalRequests = 20, #data I supply
userDisplay = (select addedName from table_a where addedUser = 1 limit 1), 
userFriends = (select group_concat(addedName) from table_a where addedUser = 1 limit 1) 
where 
userId = 1 and userName = 'norman';

table_b

"id"    "userId"    "userName"  "userDisplay"   "userFriends"               "totalFriends"  "totalRequests"
"1"     "1"         "norman"    "james"         "james,kirk,lars"   "20"            "20"

我运行上面的sql,这给了我正在寻找的结果。除此之外,我可以用其他方式做到这一点,以避免在那里使用两个select语句吗?

实际情况比这复杂得多。为了这个问题,我已经把事情搞砸了。

1 个答案:

答案 0 :(得分:2)

你可以做的是编写一个select语句,它包含一些常量值(对于你提供的数据)。例如,您可以编写此声明:

SELECT addedName AS userDisplay, GROUP_CONCAT(addedName) AS userFriends, 20 AS totalFriends, 20 AS totalRequests
FROM table_a
WHERE addedUser = 1
LIMIT 1;

然后,您可以在UPDATE语句中使用它,如下所示:

UPDATE table_b b
JOIN(
  SELECT addedUser, addedName AS userDisplay, GROUP_CONCAT(addedName) AS userFriends, 20 AS totalFriends, 20 AS totalRequests
  FROM table_a
  WHERE addedUser = 1
  LIMIT 1) temp ON temp.addedUser = b.userid
SET
  b.totalFriends = temp.totalFRiends,
  b.totalRequests = temp.totalRequests,
  b.userDisplay = temp.userDisplay,
  b.userFriends = temp.userFriends
WHERE b.userid = 1 AND b.username = 'Norman';

它在SQL Fiddle中为我工作。