MySQL查询从不同数据库中的表更新一个表中的所有列

时间:2015-06-01 16:40:06

标签: mysql

我需要在另一个数据库中将所有数据从一个表更新为相同的表(布局明智)。这可能吗?到目前为止,我已尝试过以下(仅限名字,但理想情况下我希望所有列都不单独列出。)

我尝试修复的数据只影响50到266之间的用户ID

这给了我一个语法错误

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

注 - 数据位于不同数据库的同一布局表上

2 个答案:

答案 0 :(得分:1)

试试这个(将在同一个数据库的表中工作,很可能不会在不同的数据库上工作)

UPDATE
   foundation-restore.archive INNER JOIN  foundation.archive
ON  foundation-restore.archive.user_id = foundation.archive.user_id 
SET
   foundation-restore.archive.FName = foundation.archive.FName  
WHERE foundation-restore.archive.user_id BETWEEN  50  AND 266;

答案 1 :(得分:0)

您希望将备用数据库表中的所有列数据复制到不同数据库中的其他数据库表。

要做到这一点,你必须做很多技巧。

这是最终的SQL

SET @Source_Database = "your-source-database";
SET @Dest_Database = "your-destination-database";
SET @Table = "your-table";
SET @Key_Field = "key-field-of-table";
SET @SetStr = (
SELECT 
  GROUP_CONCAT(CONCAT(@Dest_Database,".",@Table,".",COLUMN_NAME," = ",@Source_Database,".",@Table,".",COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA=@Source_Database 
  AND TABLE_NAME=@Table
  AND COLUMN_KEY<>"PRI");


set @SQLStr = CONCAT(
  "update ",@Dest_Database,".",@Table,
  " inner join ",@Source_Database,".",@Table,
  " on ",@Dest_Database,".",@Table,".",@Key_Field,
  " = ",@Source_Database,".",@Table,".",@Key_Field,
  " set ",@SetStr,
  " where ",@Dest_Database,".",@Table,".",@Key_Field ," < 10"
  );

PREPARE SQL1 FROM @SQLStr;

EXECUTE SQL1;

<强>通知

1st:我们需要知道所有字段名称并放置set子句,所以我们使用 INFORMATION_SCHEMA

SELECT 
  COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA=@Source_Database 
  AND TABLE_NAME=@Table
  AND COLUMN_KEY<>"PRI"

第二名我们使用 group_concat 函数获取单行中的所有字段

  

GROUP_CONCAT(COLUMN_NAME)

并添加concat函数以创建SET Clause

的方案
set @SetStr = (
SELECT 
  GROUP_CONCAT(CONCAT(@Dest_Database,".",@Table,".",COLUMN_NAME," = ",@Source_Database,".",@Table,".",COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA=@Source_Database 
  AND TABLE_NAME=@Table
  AND COLUMN_KEY<>"PRI");

3rd:我们使用PREPARE和EXECUTE语句声明一个SQL字符串并执行它。

PREPARE SQL1 FROM @SQLStr;

EXECUTE SQL1;

最好的问候。