Home > Database > Mysql Tutorial > How to Correctly Update MySQL Data Using INNER JOIN?

How to Correctly Update MySQL Data Using INNER JOIN?

Barbara Streisand
Release: 2024-12-08 00:34:11
Original
757 people have browsed it

How to Correctly Update MySQL Data Using INNER JOIN?

MySQL Query Using Inner Join for Updates

A user recently encountered an error while attempting to execute an UPDATE statement using an INNER JOIN in MySQL 5.0. The error occurred despite using correct field names.

The original query is as follows:

UPDATE  b
SET b.mapx = g.latitude,
    b.mapy = g.longitude
FROM business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
WHERE (b.mapx = '' OR b.mapx = 0) AND
      g.latitude > 0
Copy after login

The issue lies in the syntax of the query. To resolve it, the tables must be explicitly named in the UPDATE statement. The corrected query is:

UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0
Copy after login

The user also encountered a syntax error. To confirm that the corrected query does not contain syntax errors, the following tables were created for testing:

CREATE TABLE business (business_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, mapx VARCHAR(255), mapy VARCHAR(255)) ENGINE=INNODB;

CREATE TABLE business_geocode (business_geocode_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, business_id INT UNSIGNED NOT NULL, latitude VARCHAR(255) NOT NULL, longitude VARCHAR(255) NOT NULL, FOREIGN KEY (business_id) REFERENCES business(business_id)) ENGINE=INNODB;
Copy after login

When executing the corrected query against these tables using MySQL 5.5.8, no syntax error occurred. The query result shows that no rows were matched or changed.

The above is the detailed content of How to Correctly Update MySQL Data Using INNER JOIN?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template