我有下表:
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)
country = $country && name = $name
行。$index = name_index
。我可以使用许多查询执行以下操作,但我正在寻找一种有效的方法,只使用一个查询。这可能吗?
答案 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";
}
}
希望这会有所帮助:)。