Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

mysql - Get primarys keys affected after select, update or insert only using SQL?

How to get the primary key (assuming know his name by looking show keys) resulting from an insert into? How to get the primary keys of rows affected by an update? (as in the previous case, independent of the key name). How to get the primary keys returned from a select query (in the query even if the key is not one of the fields surveyed).

I need to SQLs commands I run after the inserts, updates and selects in my application to obtain such information, it is possible? My database is MySQL.

I need only sqls because i am making a logic of cache queries to aplicate in many applications (java and php) and i wish that the logic be independent of language.

example:

select name from people

i need that a query executed after this return the pk of these people

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT LAST_INSERT_ID();

And seriously, putting "primary key from insert mysql" into Google gets you a Stack Overflow answer as the first result.

EDIT: more discussion based on comments.

If you want to see what rows are affected by an update, just do a SELECT with the same WHERE clause and JOIN criteria as the UPDATE statement, e.g.:

UPDATE foo SET a = 5 WHERE b > 10;

SELECT id FROM foo WHERE b > 10;

If you are INSERTing into a table that does not have an auto-increment primary key, you don't need to do anything special. You already know what the new primary key is, because you set it yourself in the INSERT statement. If you want code that can handle INSERT statements coming from outside of the code that will be tracking PK changes, then you'll either need to parse the INSERT statement, or have the calling code provide information about the primary key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...