Need something like alias in insert table - mysql

I want to insert a value into a table. However that value comes from that table too. And I want to check if there is a duplicate key on that table. Since this value come from that table too, the query says that a column name is ambiguous.
$result2 = "INSERT INTO estock_saldo
(items, customer_id, quantity , reference_no, size)
SELECT
items, '".$member_id."', '".$quantity[$i]."', reference_no, size
FROM
estock_saldo
WHERE id in ({$order_id[$i]})
ON DUPLICATE KEY
UPDATE estock_saldo.quantity = estock_saldo.quantity - '".$quantity[$i]."'";
$res2 = $mysqli->query($result2);
if(!$res2){ printf("Errormessage 2: %s\n", $mysqli->error); die(); }
The ambiguous come from estock_saldo.quantity. I have tried to alias the column name. However you can't do that in insert table.

Problem persist in the below shown code snippet. You can't use column alias in INSERT statement.
INSERT INTO estock_saldo
(items, customer_id, quantity AS asquan
<-- HERE
What you are trying will always have a duplicate entry, since you are inserting the same record again. Instead of INSERT statement, you actually meant to do a UPDATE like
UPDATE estock_saldo SET
quantity = quantity - '".$quantity[$i]."'"
WHERE id in ({$order_id[$i]});

Related

Insert foreign key into table

I have two tables.
basically i want to insert an id and a string into a table
However, id is a foreign key to another table in which customerId is the primary key
Furthermore my parent table has name
What i have, is name and the stringthat i get from a web ui. However, since i dont have the id that match the customerid of name in the parent table, i don't know how to insert it.
i got this so far, which by the way is my silly attempt to work my human logic around this issue:
INSERT INTO `PostDb`(`Offer`)
VALUES ("String") AND PostDb.id
WHERE CustomerDb.id = PostDb.id AND CustomerDb.name = "MyNameThatIHave"
What would work though. is that i do the following:
SELECT PostDb.id
FROM `PostDb` JOIN CustomerDb
WHERE `CustomerId` = CustomerDb.id AND CustomerDb.name = "MyNameThatIHave"
And then use the id that i get in a new insert command like this:
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
VALUES ("THE ID I GOT BEFORE","STRING")
Basically i want to achieve in ONE query, what the two before stated queries does
You can use SELECT to get values for insert:
INSERT INTO `PostDb`(`Offer`, customerid)
SELECT 'Whatever', id FROM customerdb
WHERE name = 'MyNameThatIHave'
Have you tried LAST_INSERT_ID() function which gives you the last inserted ID PK provided that ID is an auto_increment column.
Once you get that, then you can insert in your child table in your FK column along with the rest attributes.
In that case, use a INSERT INTO .. SELECT FROM construct like
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
SELECT PostDb.`CustomerId`, 'Some Value'
FROM `PostDb` JOIN CustomerDb
ON `PostDb`.`CustomerId` = CustomerDb.id
WHERE CustomerDb.name = "MyNameThatIHave";

How to make insert or delete?

Structure table:
id (int primary key)
name (varchar 100)
date(datetime)
For insert I use query:
INSERT INTO table (name, date) VALUES ('t1','$date');
For delete row I use query:
DELETE FROM table WHERE name = 't1';
I would like want how make 1 query: first insert, if row with it name already exist, than delete row, and insert again.
Tell me please how to make it?
Create a UNIQUE index over your name column:
ALTER TABLE `table` ADD UNIQUE (name);
If you genuinely want to "delete row and insert again", then you can use REPLACE instead of INSERT. As documented:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Therefore, in your case:
REPLACE INTO `table` (name, date) VALUES ('t1','$date');
However, if instead of deleting the existing record and then inserting a new one you merely want to update the existing record, you can use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO `table` (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = VALUES(date);
The most material difference is in the treatment of columns for which you do not provide explicit values (such as id in your example): REPLACE will result in the new record having the default value, whereas INSERT ... ON DUPLICATE KEY UPDATE will result in the old value being retained.
What you want to do is use MySQL's on duplicate update feature.
Can be used like this :
INSERT INTO table (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE name=VALUES(name),dateVALUES(date);
Of course for that to happen a dupliate violation must occur.
insert into table (name, date) values('t1','$date') on duplicate key update name=values(name), date=values(date)
Are you looking for an update query?
Update will set a value on an already existing row.
UPDATE table SET date = '$newdate' WHERE name = 't1';
The best way to do this is using the mysql methods together with your query.
If you make the 'name' field unique:
id (int primary key)
name (varchar 100) NOT NULL UNIQUE
date(datetime)
And alter the query to:
INSERT INTO table
(name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = "$date"

Insert a record only if it is not present

I need to create a query to insert some records, the record must be unique. If it exists I need the recorded ID else if it doesnt exist I want insert it and get the new ID. I wrote that query but it doesnt work.
SELECT id FROM tags WHERE slug = 'category_x'
WHERE NO EXISTS (INSERT INTO tags('name', 'slug') VALUES('Category X','category_x'));
It's called UPSERT (i.e. UPdate or inSERT).
INSERT INTO tags
('name', 'slug')
VALUES('Category X','category_x')
ON DUPLICATE KEY UPDATE
'slug' = 'category_x'
MySql Reference: 13.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE Syntax
Try something like...
IF (NOT EXISTS (SELECT id FROM tags WHERE slug = 'category_x'))
BEGIN
INSERT INTO tags('name', 'slug') VALUES('Category X','category_x');
END
ELSE
BEGIN
SELECT id FROM tags WHERE slug = 'category_x'
END
But you can leave the ELSE part and SELECT the id, this way the query will always return the id, irrespective of the insert...
MySQL has nice REPLACE. It is easy to use and remember it's syntax as same as INSERT.
in you case, just run following query.
REPLACE INTO tags('name', 'slug') VALUES('Category X','category_x')
It acts like INSERT when no unique constraint violation. If duplicated value found on PK or UNIQUE key, then other columns will be UPDATED with given values. It is done by DELETE duplicated record and INSERT new record.

How do I insert the value of an auto-increment ID column into another column on inserting into MySQL table?

The first column in my MySQL table contains an auto increment ID. I would like to enter this value into another column when inserting a new row into the table, i.e. I need to read the value in the ID column and insert it into the next column.
Is it possible to do this, and if so, how?
I'm sure some of the above answers work, but I wasn't able to work out how to implement them. I did however successfully implement a solution using $pdo->lastInsertId(), i.e. after executing my INSERT query I added:
$new_id = $pdo->lastInsertId();
$sth2 = $pdo->prepare("UPDATE `tracks` SET `fav_id`= IF(`fav_id`=0,$new_id,fav_id) WHERE `id`=$new_id");
$sth2->execute();
And this sets the fav_id column of the last inserted row to the same value as the id column for this row, if fav_id has not already been set.
This should work:
INSERT INTO table(id, same_id, col1)
(
SELECT NULL AS id,
(SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA=DATABASE() AND
TABLE_NAME='table') AS same_id,
"value" AS col1
);
EDIT: As pointed by Jonathan Swartz it does suffer from race condition.
To fix this use LAST_INSERT_ID() to get the last inserted id and update this value in new column:
INSERT INTO table(id, same_id, col1)
(
SELECT NULL AS id,
NULL AS same_id,
"value" AS col1
);
SELECT LAST_INSERT_ID() INTO #var_id;
UPDATE table
SET same_id = #var_id
WHERE id = #var_id;
a simple trigger can do the job.
It will be called on when the row is inserted in table 1
and will take the Id from it and file insert into table 2
check manual
You can use mysqli_insert_id if you are using PHP on this.
Example.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
You may make second column autoincremented too (with matching AUTOINCREMENT initial value), with or without any keys.

Copying rows in MySQL

I want to copy all of the columns of a row, but not have to specify every column. I am aware of the syntax at http://dev.mysql.com/doc/refman/5.1/en/insert-select.html but I see no way to ignore a column.
For my example, I am trying to copy all the columns of a row to a new row, except for the primary key.
Is there a way to do that without having to write the query with every field in it?
If your id or primary key column is an auto_increment you can use a temp table:
CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id='7';
UPDATE temp_table SET id='100' WHERE id='7';
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
so in this way you can copy all data in row id='7' and then assign
new value '100' (or whatever value falls above the range of your current auto_increment value in source_table).
Edit: Mind the ; after the statments :)
You'll need to list out the columns that you want to select if you aren't selecting them all. Copy/Paste is your friend.
This is a PHP script that I wrote to do this, it will assume that your first col is your auto increment.
$sql = "SELECT * FROM table_name LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
for ($i = 1; $i < mysql_num_fields($res); $i++) {
$col_names .= mysql_field_name($res, $i).", ";
}
$col_names = substr($col_names, 0, -2);
$sql = "INSERT INTO table_name (".$col_names.") SELECT ".$col_names." FROM table_name WHERE condition ";
$res = mysql_query($sql) or die(mysql_error());
If you don't specify the columns you have to keep the entries in order. For example:
INSERT INTO `users` (`ID`, `Email`, `UserName`) VALUES
(1, 'so#so.com', 'StackOverflow')
Would work but
INSERT INTO `users` VALUES
('so#so.com', 'StackOverflow')
would place the Email at the ID column so it's no good.
Try writing the columns once like:
INSERT INTO `users` (`Email`, `UserName`) VALUES
('so#so.com', 'StackOverflow'),
('so2#so.com', 'StackOverflow2'),
('so3#so.com', 'StackOverflow3'),
etc...
I think there's a limit to how many rows you can insert with that method though.
No, this isn't possible.
But it's easy to get the column list and just delete which one you don't want copied this process can also be done through code etc.
Copy the table to a new one, then delete the column you don't want. Simple.
I'm assuming that since you want to omit the primary key that it is an auto_increment column and you want MySQL to autogenerate the next value in the sequence.
Given that, assuming that you do not need to do bulk inserts via the insert into ... select from method, the following will work for single/multi record inserts:
insert into mytable (null, 'a', 'b', 'c');
Where the first column is your auto_incremented primary key and the others are your other columns on the table. When MySQL sees a null (or 0) for an auto_incremented column it will automatically replace the null with the next valid value (see this link for more information). This functionality can be disabled by disabling the NO_AUTO_VALUE_ON_ZERO sql mode described in that link.
Let me know if you have any questions.
-Dipin