I want to save some data from an external source that has no id other than the data itself (eg. Red, Used, Volvo etc. from the ebay api).
So I have set up my tables like so:
aspectHeaders
id INT AUTO_INCREMENT PRIMARY KEY
name varchar(30)
UNIQUE KEY `NAME`(`name`)
aspects
id INT AUTO_INCREMENT PRIMARY KEY
name varchar(30)
aspectHeader_id INT
UNIQUE KEY `DETAIL` (`aspectHeader_id`,`name`)
aspectHeaders would contain:
7 Manufacturer
and aspects would contain:
1 Volvo 7
So in 2 stages I could check for the existence of any given data in either table and then insert it if it doesn’t exist. But my question is can I do it in 1 stage? That is, is there code to check if the data exists and insert it if not and either way return the id?
Hope this is verbose enough.
Thanks
2
Answers
If by “code” you mean a single MySQL statement, I don’t think there is. Or at least I don’t think there is without making an overly-complicated multi-query query.
Just make an
alreadyExists()
method (or something) and check before insert – something like:I usually use a method like touch() for this that does all the magic internally.