views:

741

answers:

3

Hello,

I would like to create an auto increment function that allows me to maintain uniqueness in designated columns across multiple tables.

I understand that this is not supported under mysql's standard functions, but it appears that this can be done by hand. Could someone point me in the right direction?

Thanks

A: 

You have a few choices. One, you could make the id a UUID (a 36+ varchar field), and use MySQL's UUID() function. Another option is to use a table as kind of a sequence generating table, allowing you to use the auto_increment features, and just use whatever is generated when instering into this table as a key elsewhere.

Personally, I'd opt for a UUID as that's a pretty common way to have globally unique identifiers. A word of warning: you may be better off generating these UID's in your client's language instead of using MySQL's implementation.

joeslice
A: 

what's the problem with setting column (ID) to primary/unique and auto_increment?

ps: moreover, if you require uniqueness among multiple tables, you are probably doing something incorrectly.

dusoft
using uniqueness across multiple tables is not my only option, however I would prefer it over merging two tables and adding a type column. Plus, the two tables contain different data for the two types of information. Merging the data sets would thus result in excess nulls.
dittle
i still don't understand why you couldn't have master table with primary IDs for every subtable. that's why we call mysql relational.
dusoft
i guess that could be done if i used triggers to generate the values in the secondary tables. still, it would be nice to have it all dealt with in one function.
dittle
A: 

Think this can be something like this

delimiter $$
CREATE PROCEDURE myProc()
BEGIN
DECLARE mid INT;
START TRANSACTION;
select MAX(id) + 1 INTO mid (  SELECT id FROM tbl1 UNION ALL SELECT id from tbl2 ... ) tbls;
INSERT INTO <somt_tbl> VALUES ( mid, ... ); 
COMMIT;
END$$
StarWind Software
@Paul Svirin: I'd suggest adding that signature line into your profile. The standard practice here on SO is to only provide links that will help folks solve an answer. Shameless self plugs are discouraged and nobody uses a signature line like you are.
RSolberg