Mysql - Adding Records - mysql

If two individual records are added to a database such as two patients being added to the table 'Paitents' and when they are added the Primary_Key such as Paitient_ID is created automatically and given to each new account.
.(Auto Incremented)
That bit is quite straight forward and understand I can just use an 'INSERT INTO SONGS' statement.
But what if the two patients are related and I have another table called "Relations"
Where by I need it to pull in the two Paitent_ID's and create a relation from the same insert query. Can this be done?

ID generated by MySQL automatically in auto_increment column can be obtained using the LAST_INSERT_ID() function. Languages/libraries often offer a function for this (e.g. in PHP PDO you call PDO::lastInsertId() instead of making another query).
How to solve this exactly depends on how you are inserting the values into a database, but the basics can be:
Insert patient one
Get the ID
Insert patient two
Get the ID
Create the relation

Related

Insert statement yields different results than the select all in sql

I'm currently trying to create a table of theater locations that only has three locations. I imported denormalized data that I tried to normalize with this statement:
insert into theater(`name`, email, address, phone)
select distinct theater, theater_email, theater_address, theater_phone
from denormalized_tickets;
when I comment out the first line and run it I get the result I'm looking for.
When I write a query to see the theater table select * from theater;, it returns the theaters duplicated each 12 times.
How should I solve this? Is there anything I'm overlooking?
As discussed in the comments above, INSERT creates new rows each time you execute it. If you do that multiple times, you may add more rows every time.
Vasya recommended creating a UNIQUE index to block new rows from being created with the same values. This may or may not be appropriate for a given table. For instance, what if you want to allow multiple rows to have the same values?
Another thing you might like to read about is MySQL's REPLACE statement. The syntax is similar to INSERT, but if there's a duplicate in column(s) of a primary key or unique key, it first deletes the old row and then inserts the new row. But this won't help if you don't have the unique key defined, because how would MySQL know it's a conflict?

Query optimation for insert to database

I need a solution to insert a lot of rows in concurrent time in my sql DB.
I have a rule, that everytime I insert to my transaction table, I need a unique ID that's composed by currentTime+transactionSource+sequenceNumber. my problem is, when I test my service using Jmeter, the service is down when the concurrent insert process is up to 3000 rows. the problem relies on, the duplication of the unique ID I generate. so, there are some duplications. in my assumption, the duplication happen because a previous insert process hasnt finished, but there's another insert process. So,it generates unique ID duplication.
Can anyone give me suggestion in what the best way for doing this? Thank you.
MySQL has three wonderful methods to ensure that an id is unique:
auto_increment columns
uuid()
uuid_short()
Use them! The most common way to implement a unique id is the first one:
create table t (
t_id int auto_increment primar key,
. . .
)
I strongly, strongly advise you not to maintain your own id. You get race conditions (as you have seen). Your code will be less efficient than the code in the database. If you need the separate components, you can implement them as columns in the table.
In other words, your fundamental problem is your "rule". And there are zillions of databases in the world that work perfectly well without such a rule.
Why don't you let the database handle the insert id and then update the row with a secondary field containing the format you want ? If you have dupplicates, you can always append the row id to this identifier so it will always be unique.

Query newly inserted records in a table without auto increment field

I am working with a existing database's table from another application. I want to query newly inserted records in a fixed interval.
Normally, in a table with AUTO INCREMENT id, I can store the last fetched id and use it in the query like WHERE id > :last_id. However, this table doesn't use AUTO INCREMENT id but use uuid as primary key. So is there any way to fetch new records only?
This DB is using MySQL. I can't change the database structure. The data size is quite huge so I don't think passing fetched uuids in query like WHERE uuid NOT IN (:fetch_uuids) will be a viable solution.
Edit:
There is created field, but unfortunately there is no warranty that the records with smaller created will be inserted first. So there is the risk of missing records using it.
The data were inserted by other application, and I only have read permission in this database.
Your question doesn't state whether there is a column containing the creation time of the record. If this exists then you could use this.
You have stated you cannot change the table structure, but are you sure you cannot add columns onto the existing structure? Your problem could be solved by adding an auto-increment 'secondary' ID and/or record creation timestamp. If you cannot modify the existing tables, could you perhaps create a new table with this additional information?
A solution to your problem may be in this answer. You may be able to either add an additional column to the existing table, or alternatively insert ids into a new table where you create an ID based on a TRIGGER from the original table

MySQL Trigger to update corresponding column in another table

I'm trying to write a MySQL trigger for a table update (and a similar one for insert) that will take the updated columns and update corresponding columns in another table.
My set-up is this: I have one table (A) with several columns of numerical values and a record number Primary Key. I have another table (B) with identical column names but with short text descriptors that relate to each numerical value and also a record number as a Foreign Key referring to table A. Both of these tables may grow over time to include more columns - always matching each other - each with a simple predictable name (sticking with integers for now). All records are 1:1.
My hope was that I could write triggers for both update and insert on table A that would look at the numbers and, based on some simple logic, assign a descriptor to the corresponding record in table B (inserting that record in the case of the insert trigger). It got rather complicated quickly because I had to query INFORMATION_SCHEMA.COLUMNS to identify all current column names in table A, check each OLD vs NEW to verify that column was updated (for the update trigger anyway), do some logic to determine the appropriate descriptor, then INSERT/UPDATE the corresponding column in table B. I can't figure out how to set up a procedure/trigger that doesn't require storing column names in a variable to dynamically build an SQL statement. This is, of course, not allowed in a trigger and I have made some attempts at getting around this by moving the dynamic SQL statement into a separate stored procedure. None of this has worked and I've run into so many roadblocks, I'm coming to the conclusion that I'm going about this in entirely the wrong way.
Since I'm very new to database design, I just don't know what question to ask at this point other than, is there a better way or alternatively, is there a fix to my approach outlined above?
As always, I've searched thoroughly and not found any questions that answer mine but, if you see one that does, please point me that way!

Guid Generation- SQL Latest Record

I know Guid are randomly generated, Is there any way I can find out which one is latest Guid? As I have to get the latest inserted record in my table as my table has no timeContext column.
Thank you
No, you cannot get this information.
If you need information, such as when a row was inserted, then you need to add a column to your table to track that information.
If you're trying to mimic the "chained insert" style of inserts, where a row is inserted into one table, the IDENTITY() value is obtained, then used to insert into further tables, you can instead generate the Guid value before the first insert - indeed, it's one of the advantages of GUID identifiers that a whole set of related table changes can be prepared in isolation, without accessing the database at all.