如何在MySQL中使用UPDATE和SELECT

时间:2010-11-29 23:15:21

标签: sql mysql mysql-error-1064

我正在使用最新的MySQL。

我有两个表:backlinkspages

我正在尝试更新表cache_links中名为pages的列以获取特定网址。该列应该等于backlinksdestination = url的行数。

我可以用我的应用程序语言这样做,以防我的意思不明确:

$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'");

我一直在尝试构建的查询看起来像这样:

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/'

我认为问题出在backlinks.count(*)。我不知道我做错了什么。我得到的错误是:

#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

非常感谢任何帮助。万分感谢!

1 个答案:

答案 0 :(得分:8)

您可以使用相关的子查询。

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/'