MySQL: obtain primary key value generated by before-insert trigger - mysql

In MySQL, is there any way to obtain a primary key value generated by a before-insert trigger?
I know that select last_insert_id() can return the first value of an auto_increment column from a previous insert, but I can't seem to get it to work with a trigger-generated primary key.
There is no other unique key on my table, so I won't be able to perform a subsequent select to determine the generated primary key by just using data that was used in the insert.

Related

Should I select auto-increment and primary key for the same SQL table column

I am creating a MySQL table with a primary key column; should I also select the auto-increment option or does primary key already do that?
Definitely You should select both.
and the reason why you select both is below
Auto-increment allows a unique number to be generated automatically
when a new record is inserted into a table.
Often this is the primary key field that we would like to be created
automatically every time a new record is inserted.

ON DUPLICATE KEY UPDATE only for primary keys?

Is there a way to restrict "ON DUPLICAYE KEY UPDATE" to only trigger if the duplicate key is the PRIMARY KEY of the table? (and not if the conflict is generated by a UNIQUE KEY)
For example in the following table:
CREATE TABLE users (
id INT(16) UNSIGNED AUTO_INCREMENT,
username VARCHAR(255) NOT NULL UNIQUE,
PRIMARY KEY (id),
UNIQUE (username)
);
I would like to trigger the update only if the id column generate the conflict, and throw an error as usual in case the conflict happened because of the unique key username.
Edit:
I'm working on a very simple PHP framework. Previously I had a single method save() that discriminated between INSERT and UPDATE based on the presence of the id property on the object on which it was called.
Now I rewrote this method using the INSERT INTO ... ON DUPLICATE KEY UPDATE query, but when I try to insert (for example) a user with an already existing username value, it updates that user instead of throwing an error.
I know this is the correct behaviour, I just wanted to know if there's a way to achieve the same result only on the PRIMARY KEY.
on duplicate key triggers for both primary keys and unique keys.
In your case, the primary key is an auto-incremented column, so you should not be inserting a value. Period.
Hence, you can get the behavior you want by simply not including the on duplicate key clause and leaving out the id from the insert.

Insert zero as PK for table with auto-increment primary key

I have a table with an auto-increment primary key. I have a special case need to have a record with a PK value of zero. Based on mysql can't insert record with unsigned primary key being zero, I see I can do so by executing SET sql_mode='NO_AUTO_VALUE_ON_ZERO'; before the insert.
In another session where this flag will not be set, I want to be able to utilize the default auto-increment functionality by inserting 0 or NULL.
Will there be any horrific consequences for doing this?

How to don´t repeat values stored in database

I´m creating a database addrees and I want to know what I need to set in Mysql to don´t store repeat values?
Like
Addrees 1 ("teste",1,new york,eua);
Addrees 2 ("teste",1,new york,eua);
If this happen my database will not store.
So what I need to do?
To alter an already existing table, run this MySQL command:
alter table yourtablename add unique index(firstcolumn, secondcolumn, thirdcolumn, fourthcolumn);
That'll add the unique constraint to the specified columns. Here's how to specify such a constraint in the CREATE TABLE.
CREATE TABLE buyers (
buyer_id INT UNSIGNED NOT NULL,
first_name CHAR(19) NOT NULL,
last_name CHAR(19) NOT NULL,
age SMALLINT NOT NULL,
post_code SMALLINT NOT NULL,
UNIQUE idx_flname_age (first_name,last_name,age)
);
The primary key constraint will do this too, as mentioned by #Ajeesh
EDIT:
As per the suggestion in the comment, if you want to avoid errors generated by this unique constraint, you have three good options:
INSERT IGNORE
and
INSERT...ON DUPLICATE KEY UPDATE
and
REPLACE
INSERT IGNORE will not do anything if the insert violates the unique constraint, except log a harmless warning. The table will be left as is, and no error would be reported. This may be desireable in some cases.
More commonly is the second option, ON DUPLICATE KEY UPDATE, which says "Well, if the key already exists, then update that key's row like this instead."
And lastly is REPLACE, which will, if the key already exists, delete the row, then do an INSERT as normal. If the key did not exist previously, it will simply act as an INSERT.
This stack overflow answer has some examples.
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You need to call these fields a UNIQUE_KEY
To make a column to be distinct you need to have Primary Key constraint/Unique Key. Primary key is used for relating one table with another and it's values should not be NULL. But in your case you can have Unique constraint to store only unique/distinct values.

Theoretical solution about implementing foreign key related data

How would you implement the following?
I would like to insert data to mysql tables. Let's imagine there are two tables where a foreign key relation exists. First, i insert a row that has a primary key that should be inserted as a foreign key to one of the rows to the other table. So when i would like to insert the foreign key and it's related data, i have to know the primary key of the related row in the other table. As i am a beginner, my solution would be the following: I would insert a field value with a particular data to the original table so that the inserted value could be used to retrieve the primary key with a SELECT, and then insert the retrieved primary key as the foreign key to the related rows of the other table.
Although I don't know a better solution, I think this would be a very clumsy way to implement this logic. There must be a better way of doing this.
Your solution won't work because if you are inserting not unique data, you may not retrieve the appropriate primary key. MySQL offers LAST_INSERT_ID() function for this. Just insert row into your primary key table and then use SELECT LAST_INSERT_ID(). It returns last primary key value inserted into your original table (last insert query) and now you can use it as foreign key in related table.