This question already has an answer here:
Syntax error on MERGE statement
(1 answer)
Closed 9 years ago.
Here is my current statement
INSERT INTO TABLE (LAST_NAME, FIRST_NAME, DOB, ACCESSION, EXAM_DESC, LOCATION, EXAM_DATE, REFERRING)
VALUES (${patientIdentification_patientName_familyName},${patientIdentification_patientName_givenName},${patientIdentification_dateOrTimeOfBirth_value},${commonOrder_placerOrderNumber_entityIdentifier},${observationRequest_relevantClinicalInfo_value},${patientVisit_assignedPatientLocation_facility},${observationRequest_observationDateOrTime_value},${observationRequest_orderingProvider_familyName})
ACCESSION is unique in the db. What I need to do is if the ACCESSION value already exists then I want to replace the row. If it does not exist (the value of ACCESSION is unique) I want it to INSERT.
I assume from your variables that you are using php to do this. Correct me if i am wrong.
This is how you would check if it exists:
$result = mysql_query("SELECT * FROM DBTable WHERE ACCESSION = '$ACCESSION'");
$row = mysql_fetch_array($result);
if($row > 0)
{
//code for when the record exists (update)
}
else
{
//code for when the record does not exist (insert)
}
Follow this and modify it for your dbtable and values etc.
This should do what u want it to do
Related
This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 6 years ago.
I tried using from mySQL the If Exists statement but i got an error from mysql saying there's a #1064 syntax error, but i really couldn't find it. There are my codes:
If EXISTS (select * from points where username= 'john')
update points set points = "4" where username='john'
ELSE
insert into points (username, points) values ('john', 5);
You have a syntax error in your statement. You are missing "THEN" keyword after EXISTS and "END IF" at the end, and also missing a semicolon on UPDATE statement. If you still want to go with this statement, it should be like this:
IF EXISTS (select * from points where username= 'john') THEN
UPDATE points set points = "4" where username = 'john';
ELSE
INSERT into points (username, points) values ('john', 5);
END IF;
Please take a note that this statement can be only used in routine such as Stored Procedure or Stored Function and not in normal SQL.
On the other hand, what #TimBiegeleisen said in his answer is a more efficient way to go.
One way to achieve your logic would be to use ON DUPLICATE KEY UPDATE while doing your INSERT:
INSERT INTO points (username, points)
VALUES ('john', 5)
ON DUPLICATE KEY UPDATE points=4
This query will insert ('john', 5') into your table, but if the primary key username john already exists, then it will points to 4.
This question already has answers here:
How to get the next auto-increment id in mysql
(21 answers)
Closed 9 years ago.
I am using MySQL.
I want to retrieve the next value that the AUTO_INCREMENT column will take without entering a new record.
create table ABC(id int(10) NOT NULL AUTO_INCREMENT,name char(10));
In oracle I would have used sequencename.nextval(); But what to I use in MySQL?
Here is why I did not use
select max(id) from ABC;
Suppose I have an entry with id=2. Now column id will take the next value as 3.
Before I create a record with id=3, If I delete the record with id=2.
The answer for query I mentioned will be 2. But I want the actual value 3, which the auto_increment column will anyway take.
Query table status like this:
SHOW TABLE STATUS WHERE `Name` = 'table_name'
Now in result you will get a column named Auto_increment. This is the value You were asking for.
In JAVA:
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
rs = stmt.executeQuery("SHOW TABLE STATUS WHERE `Name` = 'table_name'");
rs.next();
String nextid = rs.getString("Auto_increment");
Full example here: http://www.avajava.com/tutorials/lessons/how-do-i-use-jdbc-to-query-a-mysql-database.html
If I understand correctly,you could use the number of rows as indicator:
SELECT TABLE_ROWS+1
FROM information_schema.tables
WHERE table_name='tableName'
AND table_schema = DATABASE();
There is no way to guarantee what value you are going to get before inserting the row. This is mostly because you will have to lock the entire table to guarantee no other thread will do an insert with "your" next value.
You can reserve a value by starting a transaction, inserting a row, getting the value and then doing a rollback. Then you can safely use that value.
It will be much simpler to just insert the row, so maybe I'm not understanding the purpose of what you are doing.
This question already has answers here:
Get Updated Value in MySQL instead of affected rows
(5 answers)
Closed 9 years ago.
$query = "UPDATE transaction SET c_status = :status WHERE c_name = :name AND c_id = :id";
$stmt = $this->handle->prepare($query);
$stmt->bindParam(':c_status',$status,PDO::PARAM_STR);
$stmt->bindParam(':c_name',$name,PDO::PARAM_STR);
$stmt->bindParam(':c_id',$id,PDO::PARAM_STR);
return $stmt->execute();
Using the above syntax, I am able to update a record in the transaction table. However, what I only get with the return is a boolean. I want to know if there is a way I can get the transaction_id (the AUTO_INCREMENT field in the transaction table, c_id and c_name where just a column of that) and the rest of its columns?
This question is not related to PDO but to mysql in general.
UPDATE queries are not intended to return anything. To get a row from database you have to use SELECT query.
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.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is the database query faster if I insert multiple rows at once:
like
INSERT....
UNION
INSERT....
UNION
(I need to insert like 2-3000 rows)
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Source
If you have your data in a text-file, you can use LOAD DATA INFILE.
When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.
Optimizing INSERT Statements
You can find more tips on how to speed up your insert statements on the link above.
Just use a SELECT statement to get the values for many lines of the chosen columns and put these values into columns of another table in one go. As an example, columns "size" and "price" of the two tables "test_b" and "test_c" get filled with the columns "size" and "price" of table "test_a".
BEGIN;
INSERT INTO test_b (size, price)
SELECT size, price
FROM test_a;
INSERT INTO test_c (size, price)
SELECT size, price
FROM test_a;
COMMIT;
The code is embedded in BEGIN and COMMIT to run it only when both statements have worked, else the whole run up to that point gets withdrawn.
Here is a PHP solution ready for use with a n:m (many-to-many relationship) table :
// get data
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
// prepare first part of the query (before values)
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
//loop the table 1 to get all foreign keys and put it in array
foreach($table_1 as $row) {
$query_values[] = "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW())";
}
// Implode the query values array with a coma and execute the query.
$db->query($query . implode(',',$query_values));
EDIT : After #john's comment I decided to enhance this answer with a more efficient solution :
divides the query to multiple smaller queries
use rtrim() to delete last coma instead of implod()
// limit of query size (lines inserted per query)
$query_values = "";
$limit = 100;
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
foreach($table_1 as $row) {
$query_values .= "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW()),";
// entire table parsed or lines limit reached :
// -> execute and purge query_values
if($i === array_key_last($table_1)
|| fmod(++$i / $limit) == 0) {
$db->query($query . rtrim($query_values, ','));
$query_values = "";
}
}
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";