How to insert in MYSQL different data for same ID
I have a table Photos wi开发者_开发技巧th (product_id, description) like this
product_id 1 1 1 2 2I want to insert a description for the "first" product_id=1; another for the "second" product_id=1 etc. Any suggestions?
Like @Shi stated, I would look into using a unique primary key.
Otherwise, if the entries are already populated you can use something similar to:
UPDATE Photos SET description="DESCRIPTION" WHERE product_id=1 AND description="" LIMIT 1;
This will add a description to the earliest entered row with matching ID and a blank description, assuming it's not indexed using a different column.
You definitely should use a chaotic primary key, like an AUTO_INCREMENT value (http://dev.mysql.com/doc/refman/5.1/en/create-table.html).
This way, each record gets an own, unique identifier which you then can use to uniquely identify any given record.
What you want to do is create a in insert
query. Once your primary data has been inserted you use the mysql_insert_id
function to grab the id of the newly inserted row. Then, using this new id you can use the update
method to update any new data to the row you first created.
For example:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
$variables = array (
"one" => "something"
);
/* First query: */
mysql_query ("INSERT INTO mytable (product) values ('" . $variables["one"] . "')");
$new_id = mysql_insert_id();
/* Data processes... */
$variable["two"] = "Something else";
/* Second query: */
mysql_query ("UPDATE mytable SET something = '" . $variable["two"] . "' WHERE id = '" . $new_id . "');
There is no hard and fast rule that forces you to use primary keys in MySQL. You can and may create tables with no primary keys, and even with no keys or indexes, at all.
What you can define is this, with storage engine InnoDB:
CREATE TABLE photo_catalogue (
product_id INT,
description VARCHAR(128),
INDEX(product_id, description)
) engine=InnoDB
Replace VARCHAR(128) by CHAR(128), if you want to use MyISAM tables. You can optionally define the index as UNIQUE
though.
I have seen MySQL tables in production systems with millions of entries and no index, at all. On porpuse to avoid additional memory and performance issues with indexes.
精彩评论