Most efficient way to insert two rows that depend on each other - php

I have a site that is essentially a collection of links. A mysql database which stores users, links and votes. My links table has two foreign keys, user_id and vote_id. When a link is inserted into the database it will start with one vote so that means I need to insert a row into the votes table but they essentially depend on one another to exist. I need the ID of the links for the foreign key of the votes table and vice versa. My current "plan" is to insert a links row with a vote_id of 0, select the same row to get it's ID and then insert a votes row using the links row id as it's foreign key, select it's ID and update my original links row. This seems really inefficient but I need to make sure users votes are recorded for time keeping and eliminating duplicate votes. Am I going about this the wrong way?

In PHP, you can use mysql_insert_id:
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
You could use this to get the row ID of the newly inserted link.
Assuming one vote can only belong to one link, the links table should not have a vote_id column. So you shouldn't need the identity of the newly inserted vote.

Related

Transfer data from memory table to production one by criteria

I wander around can I transfer the data gathered in memory table to actual one by sql query only.
The two tables have the same structure and pk is products_id(int, AI)
The problem is the criteria is completely different than the pk. The products are identified by 2 columns - barcode and company.
So ignoring the pk in whole, I need to update the data if in actual table there is a row with the same barcode and company, and insert new record if there is none.
Tried this:
INSERT INTO products (products_sku, ...)
SELECT products_sku... FROM temp_products
WHERE (temp_products.products_barcode = products.products_barcode) AND (temp_products.products_comp = products.products_comp)
But i dont have access in the select to products table so to make the filtering
I think you need to add a unique key on products_barcode and products_comp:
ALTER TABLE products ADD UNIQUE KEY (products_barcode, products_comp);
Once you have it you can perform insert-or-update in one statement:
INSERT INTO products (/* all columns except the id */)
SELECT /* all columns except the id */
FROM products_sku
ON DUPLICATE KEY UPDATE some_field = VALUES(some_field), ...
/* list all columns except the id / barcode / comp */;
So when it meets a duplicate barcode/comp pair it will fall into the ON DUPLICATE KEY UPDATE and won't insert. Read more how it works: https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

foreign keys mysql php

I have two table in which I need to submit data. It is a directory listing website on the first table has the common data name etc but I have to manage business hours as well look below
**Users**
Users_Id Name Age AddressId .........
----+------+------+-----------
**users_hours**
hours_id Users_Id day day day .........
----+------+------+-----------
I have to make a foreign key for this but the only issue is how will I get the id of the user dynamically?
As both of these rows will be created together.
So you want to get the last insert id of Users table, for getting the last id you need to use the mysql_insert_id() here.
First make a insert query for Users and use $userId = mysql_insert_id().
The $userId now hold the last id of the Users table, so you can now make a second query for users_hours.
More about mysql-insert-id.php

Controlled table quering based on existing rows

I have a product_group table with the following fields: group_id, product_id, order. The table will be queried against a lot: a single-form view will make it possible to insert new records and/or update existing ones with one submit.
I'm trying to figure out optimal solution to cover the following 3 cases:
User tries to insert an existing row: do nothing. Here a unique index of the 3 columns can be useful.
User changes only the order column: perform an update.
User inserts a completely new set of values: perform an insert.
Is there a way to put all of this together in one MySQL query? If not, what would be the best approach here? The goal is to limit database queries as much as possible.
Does this do what you want?
insert into product_group(group_id, product_id, `order`)
values (#group_id, #product_id, #order)
on duplicate key update `order` = values(`order`);
Along with a unique index on group_id, product_id:
create unique index idx_product_group_2 on product_group(group_id, product_id)
This handles your three cases:
Because the value assignment is a no-op if the values are the same.
The order column will be updated if the other two have the same value.
A new row that has a different group_id or product_id will be inserted.
As a note, order is a lousy name for a column, because it is a SQL key word.

How do I delete a row from one table, when no more rows exist in another

I would like to know the best way to check one table of data, and when no more rows exist matching the WHERE clause, delete a row from another table.
I have tried myself but it has become too cumbersome with 6 queries and nested if/else, and it doesn't work to top it off.
I have never used SQL join's before, so examples will help me to understand responses.
I have a table of devices, there is a master table with a device and a password.
There is a second table containing the multiple rows of the device in the above table, and a series of serial numbers.
When the second table no longer contains any of the serial numbers listed in the master table, I want the row containing the device and password from the master table.
If you mean like when you have a table customer and a table order, delete the customers if they have no orders? Then you can use subselect:
delete from customer where customerid not in (select customerid from order)
You coult make a DELETE statement like
DELETE FROM masterTable WHERE ID NOT IN (SELECT masterTableID FROM secondaryTable)
This would delete all the rows from the master-table which don't have any references in the second table. That also means it would not delete only one row, but all of the matching ones. The only necessary thing you need is that every row in the second table references to the master table.
DELETE table_devices
FROM table_devices
left JOIN serial ON table_devices.id= serial.device_id
WHERE serial.device_id is null

reference auto-increment columns?

I have 2 tables that I am working with that use the same column; one table contains the text and the other table contains the images; they use the column listing_id so that the right text shows up with the right images;
my problem is that because column listing_id is auto-increment, my first table is able to have an insert into query that is able to insert the text and then +1 the column listing_id; however the 2nd table I use another INSERT INTO query will not have the right listing_id,
because some entries for listing_id have been deleted, meaning that the 2nd table's listing_id will always be behind the 1st tables listing_id;
how do I reference the column listing_id?
You need to create an INT column called something like "parent_id" in the dependant tables that stores the id of the main table that it is referencing. When you select records from the first, you would then JOIN the tables with the auto_increment field of the first field against the "parent_id" of the second.
As MrSlayer mentions, use the newly inserted ID of the first table to update "parent_id". You should typically have a unique ID field in the second table for uniqueness, but it shouldn't be part of the relationship to the first table.
If you're unclear about how to get the id that the first table auto_increments to when you insert, use mysql_insert_id().
mysql_query("INSERT INTO table1 ...");
echo "Last inserted record_id in table1 was " . mysql_insert_id();
INSERT INTO table1 (mytextcolumn) VALUES('text');
INSERT INTO table2 (parent_id,image_name) VALUES(LAST_INSERT_ID(),'someimage.png');

Categories