Next composite primary key ID

Asked

Viewed 67 times

0

I have the following example structure for the people table:

CREATE TABLE `pessoas` (
`i_entidade` int(4) UNSIGNED NOT NULL,
`i_pessoas` int(11) UNSIGNED NOT NULL,
`nome` char(60) COLLATE utf8_unicode_ci NOT NULL,
`nome_fantasia` char(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`tipo_pessoa` char(1) COLLATE utf8_unicode_ci NOT NULL,
`ativo` tinyint(1) NOT NULL,
`date_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `pessoas`
ADD PRIMARY KEY (`i_entidade`,`i_pessoas`);
COMMIT;

As it turns out the application will be multi-entity. Each entity that will have access to the register of people, can only manipulate the data related to its entity. Then follow an example of this populated table:

(pessoas)
| i_entidades | i_pessoas |  nome  |
|      1      |     1     |  João  |
|      1      |     2     |  José  |
|      2      |     1     |  João  |
|      2      |     2     |  Maria |
|      2      |     3     |  José  |
|      3      |     1     |  José  |
|      3      |     2     |  João  |

I need it first before I do the INSERT find the next key to be able to insert since composite primary key does not accept AUTO INCREMENT, then in the head comes the use of the following QUERY to get the value for entity number 1 for example:

SELECT MAX(i_pessoas)+1 AS i_pessoas FROM pessoas WHERE i_entidades = 1;

My question is, is this really the best option for this problem? Is QUERY has a particularity too that only returns NULL where there is no row inserted for that entity.

The application is being developed in the language PHP and using a bank MYSQL.

  • Since it will return NULL, you could leave this "+1" for after receiving the result in PHP. It seems safer... What do you think?

  • @Matteusbarbosa then wanted to know if it is the only option and the correct form for this situation.

  • So. You’re not the only one for me, but you came in the best way. I would do as you did, with this small change, because adding null +1 will return null.

  • And it will work. As you said, it solves the null problem. I used this technique in older projects. I will resume the project next week.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.