How to use UPDATE with a SELECT in MySQL
I am using the latest MySQL.
I have two tables: backlinks
and pages
.
I am trying to update a column called cache_links
in the table pages
for a certain url. The column should equal the number of rows in backlinks
where destination
= url
.
I could do this in my application language like so, in case what I mean to do isn't clear:
$myURL = "http://google.com/";
$numLinksResult = mysqli_query($c, "SELECT count(*) AS `num` FROM `backlinks` WHERE `same_domain` = FALSE AND `url` = '$myURL'");
$numLinksRow = mysqli_fetch_assoc($numLinksResult);
$numLinks = $numLinksRow['num'];
mysqli_query($c, "UPDATE `pages` SET `links` = $numLinks WHERE `url` = '$myURL'");
The query I've been trying to build currently looks like this:
UPDATE `pages`, `backlinks` SET pages.`cache_links` = backlinks.count(*)
WHERE backlinks.`destination` = pages.`url`
AND backlinks.`same_domain` = FALSE
AND pages.`url` = 'http://google.com/'
The pr开发者_Go百科oblem, I think, is at backlinks.count(*)
. I have no idea what I'm doing wrong. The error I get is:
#1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '*)
WHERE backlinks.`destination` = pages.`url` AND backlinks.`same_' at line 1
Any help is greatly appreciated. Thanks a ton!
You can use a correlated sub query.
UPDATE `pages`
SET pages.`cache_links` =
(SELECT COUNT(*)
FROM backlinks
WHERE backlinks.`destination` = pages.`url`
AND backlinks.`same_domain` = FALSE
)
WHERE pages.`url` = 'http://google.com/'
精彩评论