从另一个表中的数据更新一个表中的数据

时间:2020-04-05 23:26:19

标签: mysql sql

我的表symbol = str(symbol[0]) 有3列:

Customers

其他表ID (primary) city country 1 Chicago USA 2 Chicago USA 3 New York USA 4 Paris France 有2列:

locations

我在city (primary) country Chicago Null (Empty) New York Null (Empty) Paris Null (Empty) 表中创建了country列,以更新locations表中的country值。喜欢:

Customers

但是上面的查询给出了错误:UPDATE locations SET country = (SELECT country FROM customers);

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我认为您需要使用JOIN语法进行UPDATE。试试这个-

UPDATE locations L
JOIN Customers C ON C.city = L.city
SET L.COUNTRY = C.COUNTRY;

答案 1 :(得分:0)

你非常亲近

UPDATE locations l 
SET 
    country = (SELECT 
            country
        FROM
            Customers
        WHERE
            city = l.city
        LIMIT 1)
CREATE TABLE locations  (
  `city` VARCHAR(25),
  `country` VARCHAR(25)
);

INSERT INTO locations 
  (`city`, `country`)
VALUES
  ('Chicago',              Null),
  ('New York',             Null),
  ('Paris',                Null);
✓

✓
CREATE TABLE Customers  (
  `ID` INTEGER,
  `city` VARCHAR(8),
  `country` VARCHAR(6)
);

INSERT INTO Customers 
  (`ID`, `city`, `country`)
VALUES
  ('1', 'Chicago', 'USA'),
  ('2', 'Chicago', 'USA'),
  ('3', 'New York', 'USA'),
  ('4', 'Paris', 'France');
✓

✓
  <!-- -->
CREATE TABLE locations  (
  `city` VARCHAR(25),
  `country` VARCHAR(25)
);

INSERT INTO locations 
  (`city`, `country`)
VALUES
  ('Chicago',              Null),
  ('New York',             Null),
  ('Paris',                Null);
✓

✓
CREATE TABLE Customers  (
  `ID` INTEGER,
  `city` VARCHAR(8),
  `country` VARCHAR(6)
);

INSERT INTO Customers 
  (`ID`, `city`, `country`)
VALUES
  ('1', 'Chicago', 'USA'),
  ('2', 'Chicago', 'USA'),
  ('3', 'New York', 'USA'),
  ('4', 'Paris', 'France');
✓

✓
  UPdate locations l SET country = (SELECT country FROM Customers WHERE city = l.city LIMIT 1)
SELECT * From locations;
city     | country
:------- | :------
Chicago  | USA    
New York | USA    
Paris    | France 

db <>提琴here

SELECT * From locations;
city     | country
:------- | :------
Chicago  | USA    
New York | USA    
Paris    | France 

db <>提琴here

相关问题