只用一个查询解决?

时间:2014-02-04 18:48:49

标签: php mysql

我有下表:

CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB

我想:

鉴于:($country, $name, $new_index)

  1. 检查是否存在country = $country && name = $name行。
  2. 如果该行存在,请获取索引$index = name_index
  3. 如果该行不存在,请添加该行,然后获取索引。
  4. 我可以使用许多查询执行以下操作,但我正在寻找一种有效的方法,只使用一个查询。这可能吗?

1 个答案:

答案 0 :(得分:1)

只有一个查询是不可能的。

你可以这样做:

$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
   $row = mysql_fetch_row($query);
   $index = $row[0];
} else {
   $sql = "INSERT INTO (your table) (country, name)
   VALUES('$country','$name')";
   $query = mysql_query($sql);
   $check = mysql_num_rows($query);
   if($check > 0) {
      $sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
      name = '$name' LIMIT 1";
      $query = mysql_query($sql);
      $row = mysql_fetch_row($query);
      $index = $row[0];
   } else {
      echo "Error occured while trying to insert new row";
   }
}

希望这会有所帮助:)。