php - UNION mysql determine which table the result came from -


$stmt = $dbh->prepare("select id table1 union select id table2 union select id table3 order id desc limit 1"); 

the code above code auto generating id. want select last inserted id. want want last id inserted on 3 tables. can of 3 tables. , want increment id. catch need know table last id can select field , record last id has attribute. attribute depending on table why want table.

add discriminator column, , use max aggregate function each query avoid sorting huge intermediate resultset, , use union all set operator in place of union operator. (since each query return 1 row, that's not going make of difference; don't need eliminate duplicate rows, prefer union all set operator avoid unnecessary (and expensive) operation.

something should return result seem after:

( select 'table1'   source        , max(t1.id) max_id     table1 t1 ) union ( select 'table2'   source        , max(t2.id) max_id     table2 t2 ) union ( select 'table3' source      , max(t3.id) max_id   table3 t3 ) order max_id desc limit 1 

that give resultset identifies table name had maximum id.

note: assumes "last inserted id" identified maximum value. if 2 tables have same maximum id value, it's indeterminate row returned. can add source order make deterministic:

order max_id desc, source desc 

(the actual requirements aren't clear me; statement above should return same value being returned query in question, along discriminator tells table id value from.)

reference: https://dev.mysql.com/doc/refman/5.5/en/union.html


note: may satisfy use case, in more general case, advise avoiding approach id value of row last inserted.

for values of auto_increment column, value automatically assigned, last_insert_id function return id value of first row inserted preceding insert statement in same session. in multiuser system, not safe assume "highest" id value row inserted current session - approach broken.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -