0

i use MySQL. I have a table of users:

id (int primary key)
name (text)
login (text)

The table is filled in automatically. From other sources I get information from the user names in this table, take their ID. If the user is not already in the table, it should be added, and return it to ID

The scheme works out as follows:

1) get an ID on the user's behalf.

sql = "SELECT * FROM `users` WHERE `name` = 'user_name'

2) if not found, then add the user

if result is None:
    sql2 = "INSERT INTO `users` (`name`) VALUES ('user_name')

query not returns the added element ID, so you have to again make a request to know the user ID

    sql3 = "SELECT * FROM `users` WHERE `name` = 'user_name'

in the end it is necessary to make 3 query to get a user ID that is not already in the table. as it turns out a rather complicated scheme of work.

is it possible to request that, in the absence of compliance creates a record and immediately returns the data?

or may act differently? always add a new user, but to the addition did not occur in the presence of such a table. and of course to immediately return his ID?

tell me how one request to make of all this?

JayIsTooCommon
  • 1,713
  • 2
  • 19
  • 30
MaxKu
  • 754
  • 2
  • 14
  • 38
  • what does jquery have to do with this? – madalinivascu Apr 04 '16 at 08:15
  • Or python for that matter. – Ilja Everilä Apr 04 '16 at 08:20
  • Yes, in what language should this be scripted? – LinkinTED Apr 04 '16 at 08:21
  • You can ask for the ID of the last-inserted row [like this](https://stackoverflow.com/questions/2548493/how-do-i-get-the-id-after-insert-into-mysql-database-with-python). That should remove the need for your third query. – Wander Nauta Apr 04 '16 at 08:23
  • it reduces the number of requests to 2. Is it possible to do one? – MaxKu Apr 04 '16 at 08:42
  • Sure, if you want to you could skip the first SELECT by just always INSERTing a new user and doing nothing if the user already exists, [like this](https://stackoverflow.com/questions/4596390/insert-on-duplicate-key-do-nothing). That would be shorter, but less clear, I think. – Wander Nauta Apr 04 '16 at 08:50

0 Answers0