如果只有一行记录重复

时间:2014-05-06 17:07:39

标签: mysql sql

我的记录存在问题,我必须在表格中记录。如果存在同名产品,我想要更新行。

if ((int)$price > 0) {
    $query = "SELECT name FROM phones WHERE LOWER(`name`) = LOWER(?)";
    $duplicate = $this->db->query($query, array($name));
    if ($duplicate->num_rows() > 0) {
        $query = "update  phones (name,price,shop,link,photo,priority) VALUES (?,?,?,?,?,?)";
        $this->db->query($query, array($name,$price,"Pigu.lt", $link, $photos, rand(0,1000)));
    } else {
        $query = "insert into phones (name,price,shop,link,photo,priority) VALUES (?,?,?,?,?,?)";
        $this->db->query($query, array($name,$price,"Pigu.lt", $link, $photos, rand(0,1000)));
    }
}

表格结构:

 CREATE TABLE `phones` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name`   varchar(500)
 COLLATE utf8_lithuanian_ci NOT NULL, `price` int(15)
  NOT NULL, `shop`  varchar(100) 
 COLLATE utf8_lithuanian_ci NOT NULL, `link` varchar(400)
 COLLATE utf8_lithuanian_ci NOT NULL, `photo` varchar(500) 
 COLLATE utf8_lithuanian_ci NOT NULL, `priority` int(5)
 NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=544 DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;

知道代码不行,请为此提供帮助

1 个答案:

答案 0 :(得分:0)

我不知道您的PHP无法正常工作的原因,但由于您使用mysqlsql而非php标记了您的帖子,我认为您&#39 ; ll接受以SQL为中心的解决方案。这是两个;两者都假设name是表phones中的主键。

ANSI-compliant

$query = "INSERT INTO phones (name, price, shop, link, photo, priority) \
          VALUES (?,?,?,?,?,?) \
          ON DUPLICATE KEY UPDATE price=?, shop=?, link=?, photo=?, priority=?";
$randnum = rand(0, 1000);
$this->db->query($query, array($name, $price, "Pigu.lt", $link, $photos, $randnum,
                               $price, "Pigu.lt", $link, $photos, $randnum));

MySQL-only

$query = "REPLACE INTO phones (name, price, shop, link, photo, priority) \
          VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name, $price, "Pigu.lt", $link, $photos, rand(0,1000)));