i have a datagridview row, containing three string values. These values should be looked up into the Products table for finding the corresponding product ids. Then these will be inserted onto the Relations Table. I am looking for the best query to achieve this.
Here is my Products Table
+------------+--------------+
| Product_ID | Product_Name |
+------------+--------------+
| 1 | Foo |
| 2 | Bar |
| 3 | Baz |
| 4 | NewProduct |
+------------+--------------+
and the Relations Table i am trying to insert into
+------------+----------------+-----------------+
| Product_Id | RelatedProd_Id | RelatedProd_Id2 |
+------------+----------------+-----------------+
| 1 | 2 | null |
| 2 | 3 | 1 |
| 3 | null | null |
+------------+----------------+-----------------+
The below one is not a table, it is a sample datagridview Row..
+------------+--------------+---------------+
| ProdName | RelProd_Name | RelProd_Name2 |
+------------+--------------+---------------+
| NewProduct | Foo | Bar |
+------------+--------------+---------------+
I am trying to find the ids from this row and insert it into the Relations table.
I tried a dumb query..but i dont’ know the correct way of doing it..something like,
INSERT INTO PROD_RELATIONS (Product_id,RelatedProd_Id,RelatedProd_Id2)
VALUES
(SELECT Product_Id FROM Products WHERE Product_Name = 'NewProduct'),
(SELECT Product_Id FROM Products WHERE Product_Name = 'Foo'),
(SELECT Product_Id FROM Products WHERE Product_Name = 'Bar')
Can somebody guide me on this?
With your current table structure a query like this would work:
However, I’d recommend changing your relations table to a more simple layout with multiple rows per product:
This means that you don’t have to add more columns if a product has more than 2 relations. In which case your insert statement would be:
You can always query your product relations table to get it back to a 2 column format if necessary