tags:

views:

138

answers:

4

I'm dealing with a relational table and I've been wondering if there's a way to lower the number of queries I need to make when inserting data to the tables..

Here are the queries I currently use:

I insert the "main" values.

INSERT INTO products
        (title, description, status, url)
    VALUES
        ('some title', 'description of doom', 1, 'some-title');

We make it insert the value only if it doesn't exist already.

    INSERT IGNORE INTO values
            (value)
        VALUES
            ('example value');

Since I'm not sure if the query was actually inserted, I get the id..

            SELECT id
                FROM
                    values
                WHERE
                    value = 'example value';

Where "?" is the ID I got from the last query.

                INSERT INTO link
                        ( id_product, id_catalog, id_value )
                    VALUES
                        ( 33, 1, ? );

This means that each extra value I need to add will cost 3 queries. So my question is: Is there a more efficient way to do this?

A: 

"Is there a more efficient way to do this?"

No. Not really. Creating three things takes three inserts.

S.Lott
+1  A: 

You can do this to at least drop one of the queries:

INSERT INTO link
     ( id_product, id_catalog, id_value )
VALUES
     ( 33, 1, (SELECT id
                 FROM values
                WHERE value = 'example value') );

I basically am replacing the '?' with a sub select of the second query to get the id.

northpole
What happens if 'example value' already exists? Does it ignore duplicates?
Robert Harvey
depending on your constraints, you will violate them.
northpole
So...You are forcing an error?
Robert Harvey
it depends how you want to handle it. If you want to throw an exception on duplicates then create a constraint that will do so. Otherwise, unfortunately, you will be required to first query for the value like you are already doing or allow duplicates.
northpole
That being said, I don't really see anything wrong with how you are currently doing it. You are essentially doing the work of a constraint except you don't throw an exception if a dup is found, you just don't do the final insert.
northpole
Isn't a subquery the same as doing separated queries?
kuroir
no, a subquery is a query inside another query. It is one executed query and the system will do multiple queries for you. The system will optimize it as necessary. The user only has to execute one query.
northpole
A: 

You should be able to tell whether the insert succeeded with the ROW___COUNT() function from inside MySQL. If calling from another language (e.g. PHP), the mysql_query or equivalent function will return the row count.

Ken Keenan
A: 

You could use an INSERT INTO ... ON DUPLICATE KEY UPDATE statement.

This does, however, require that the primary key be one of the values for the insert, so it doesn't work on tables with an auto-increment.

R. Bemrose