is it possible to copy data from a table to another table?.
here is my example. i have two tables, warehouse and showroom
my warehouse table has (product_id and stock_quantity) and my showroom table has (product_id(fk from warehouse), stock_transferred )..
for example in warehouse table
product_id stock_quantity
1 10
2 20
how can I transfer product_id(1)with stock_quantity(5) in showroom table and still retain the data in warehouse table?
so after transferring data my warehouse table becomes these:
product_id stock_quantity
1 5
2 20
and my showroom table becomes these:
product_id stock_transferred
1 5
how can i do these in a php form?for example i have a text input in which the user can specify how many stocks he will transfer to showroom table.
sorry I cant explain well Im not good in english.
BEGIN TRAN
INSERT INTO showroom
SELECT product_id, #ValueToBeReduced FROM warehouse
WHERE product_id = 1
-- error handling
UPDATE warehouse
SET stock_quantity = stock_quantity - #ValueToBeReduced
INNER JOIN showroom
ON warehouse.product_id = showroom.product_id
AND showroom.product_id = 1
-- error handling
COMMIT TRAN
You can use insert into(select...)
Related
I have the following tables (Have only included necessary columns) which I'm looking to perform a query on. Some notes:
1) Table 1 has a one-one relationship with Tables 2 & 3, with the common key being menu_id.
Tables 4-6 are a little more complicated:
2) Table 1 has a one to many with table 4, so one menu can have many categories.
3) Table 4 has a one to many with table 5, so one category (Out of multiple above) can have many items.
4) Table 5 has again a one to many with table 6, so one item can have many subitems.
Table 1: -- user_menu --
menu_id
Table 2: -- menu_details --
menu_id
Table 3: -- menu_times --
menu_id
Table 4: -- menu_categories --
menu_category_id
menu_id
Table 5: -- menu_items --
menu_item_id
menu_category_id
Table 6: -- menu_subitems--
menu_subitem_id
menu_item_id
Question: I need a sql query which will fetch the all associated data from the tables (All columns, I haven't included them here, just the primary key rows) for a specific menu_id on table 1. That seems simple enough, but I'm struggling a little on the one to many part and getting that data in the same query.
I'm expecting something like this. Where menu_id = 2, it will fetch the associated row data (all columns). I've shortened the key names to fit.
user_menu | menu_details | menu_times | menu_categories | menu_items | menu_subitems
-------------------------------------------------------------------------------------
menu_id=2 - menu_id=2 - menu_id=2 -< cat_id=1 -< item_id=1 subitem_id=1
cat_id=2 -< item_id=2 -< subitem_id=2
cat_id=3 item_id=3 subitem_id=3
item_id=4 -< subitem_id=4
item_id=5 -< subitem_id=5
subitem_id=6
subitem_id=7
(I've shortened above. The proper names are in the first list, so please use those).
The ID's refer to the primary key rows I need the associated column data for. To clarify again If I were to query for menu_id = 2, I will get the menu_id = 2 row from table 2 & 3. I will also get the categories WHERE menu_id = 2 in the menu_categories table, the item_id rows where menu_category_id = x in the menu_item table, and the subitem rows where item_id = x from the menu_item table, in the subitem table.
I plan on copying the result to an array and passing that back. Just need the query bit (I'm assuming join but I'm not sure which is relevant here).
Thanks!
Yes, you can just use join, joining them using the key references should output it like that:
select A.menu_id, B.menu_id, C.menu_id, D.menu_category_id, E.menu_item_id,
F.menu_subitem_id
from user_menu A
join menu_details B on A.menuid = B.menuid
join menu_times C on B.menuid = C.menuid
join menu_categories D on C.menuid = D.menuid
join menu_items E on D.menu_category_id = E.menu_category_id
join menu_subitems F on E.menu_item_id = F.menu_item_id
where A.menu_id = 2
I have a table full of products including price, name, date and ID (PK)
I am in need to update the records when there is a price change (Web scraping script), how would i go about this so that a new row is NOT inserted, rather the price and date are updated.....but the previous values need to remain in the DB....so that when i when i go
"SELECT * FROM items WHERE id ='27'";
Output wanted:
$400 12.4.2013
$314 22.4.2013
$250 12.4.2013
The product will be then displayed with all the updated values since the first price was downloaded, effectively it will be a history of the prices for the item...
the actual results i want to achieve would hopefully be
History for "Product 27" is:
To give more context, when i run my script... ./script.php update
all the new data should be inserted or updated....but old values remain
im not too sure how i should approach this....please provide me with some guidance or assistance
The best way to go about this while keeping a tidy database with easily maintainable and readable data would be to take what #KishorSubedi said in the comment and create a log table.
When you update your price in your Products Table, store the old price, along with its date and ID in the Log Table then when you need to look up all the records for that product you can JOIN the Log Table in your query.
Log Table
| ProductID | Price | Date |
| 27 | $300 | 02.1.2013 |
| 27 | $400 | 03.1.2013 |
This way you can have a nice and neat Products table that is not cluttered with multiples of the same product, and an unobtrusive log table that is easily accessible.
Hope this gives you some guidance on building your site and database.
If you want to keep the old values I would suggest saving them in a seperate table and to use the INSERT statement. You are always adding a new row, so you can not bypass an insert or select into or similar statement.
Table structure:
Items
------------------------------
Id primarykey
Name
Price
------------------------------
Id primarykey autoincrement
ItemId index
AddDate index
Price
Now when you scrape the web you will just insert the new price in the Price table. If you want to select all the prices for an item you can use
SELECT Items.Id
,Items.Name
,Price.Price
,Price.AddDate
FROM Items
LEFT JOIN Price
ON Items.Id=Price.ItemId
WHERE Items.Id='27'
ORDER BY Items.Name ASC, Price.AddDate ASC
And if you just want the latest or current price, you can use
SELECT Items.Id
,Items.Name
,P1.Price
,P1.AddDate
FROM Items
LEFT JOIN Price P1
ON Items.Id=Price.ItemId
LEFT JOIN Price P2
ON P1.ItemId=P2.ItemId
AND P1.Id<P2.Id
WHERE Items.Id='27'
AND P2.Id IS NULL
Add new column for history in 'item' table and each price change append the changed value to this column with a specific format as like date1:price1,date2:price2,....
I'm struggling a bit on the best way to do this with as little performance hit as possible.
Here's the setup...
Search results page with search refining filters that make an AJAX call to a PHP handler which returns a new (refined) set of results.
I have 4 tables that contain all of the data I need to connect to in the PHP handler code.
Table 1 - Main table of records with main details
Table 2 - Ratings for each product from professional rating company #1
Table 3 - Ratings for each product from professional rating company #2
Table 4 - Ratings for each product from professional rating company #3
The refiners on the search results page are jquery sliders with ranges from the lowest allowed rating to the highest for each.
When a slider handle is moved, a new AJAX call is made with the new value(s) and the database query will run to create a fresh set of refined results.
Getting the data I need from Table 1 is the easy part. What I'm struggling with is how to efficiently include a join on the other 3 tables and only picking up rows that match the refining values/ranges. Table 2, 3, and 4 all have multiple columns for year (2004-2012) and when I made an initial attempt to put it all into one query, it bogged down.
Table 2, 3, and 4 hold the various ratings for each record in Table 1.
The columns in Table 2, 3, and 4 are...
id - productID - y2004 - y2005 - y2006 - y2007 - ... you get the idea.
Each year column has a numeric value for each record (default is 0).
What I need to do is efficiently select records that match the refiner ranges selected by the user across all 4 tables at once.
An example refiner search would be...get all records from Table 1 where price is between $25 and $50 AND where Table 2 records have a rating (from any year/column) between 1 - 4 AND where Table 3 records have a rating (from any year/column) between 80 - 100 AND where Table 4 records have a rating (from any year/column) between 80 - 100.
Any advice on how to set this up with as much performance as possible?
My suggestion would be to use a different table structure. You should merge Table 2, 3 and 4 into a single ratings table with the following structure:
id | productID | companyID | year | rating
Then you could rewrite your query as:
SELECT *
FROM products p
JOIN ratings r ON p.id = r.productID
WHERE p.price BETWEEN 25 AND 50
AND (
( r.companyID = 1 AND r.rating BETWEEN 1 AND 4 )
OR ( r.companyID = 2 AND r.rating BETWEEN 80 AND 100 )
OR ( r.companyID = 3 AND r.rating BETWEEN 80 AND 100 )
)
This way the performance would surely increase. Also, your tables will be more scalable, both with the years and the number of companies.
One more thing: if you have a lot of fields in your products table, it might be more useful to execute 2 queries instead of joining. The reason for this is that you are fetching redundant data - every joined row will have the columns for product, even though you only need it once. This is a side-effect of joins, and there is probably a performance threshold where it will be more useful to query twice than to join. It is up to you to decide if/when that is the case.
hi i cannot update a table which has foreign keys on it. in this table, instead of displaying the primary keys of the foreign key, i choose to display their names: this is a simple diagram:
Here are my foreign tables:
Size Table:
sId sName
1 1x1
2 2x2
Brand Table:
bId bName
1 brand1
2 brand2
Supplier Table:
sId sName
1 supp1
2 supp2
So here is my Warehouse Table using a join statement:
pId pName pSize pBrand pSupplier
1 prod1 1x1 brand1 supp1
2 prod2 2x2 brand2 supp2
here is my edit in php and mysql form:
########### EDIT PRODUCT
if(isset($_POST['editproduct'])){
$product_id=$_POST["product_code"];
$product_name=$_POST["product_name"];
$size_name=$_POST["size_name"];
$brand_name=$_POST["brand_name"];
$supplier_name=$_POST["supplier_name"];
$sql = "UPDATE warehouse SET
product_name='$product_name'
,size_id='$size_id'
,brand_id='$brand_id'
,supplier_id='$supplier_id'
WHERE
product_code='$product_code'";
$result=mysql_query($sql,$connection) or die(mysql_error());
header("location: warehouse.php");
} ?>
the weird thing is that the first try i edit the table it does not error. but for the second time, it prompts me the error of foreign key constraint, :(
i have a feeling that because i use a join statement in my warehouse table, that conflicts my update query since the one i am updating is the primary key and i only display its name.
you reference the variables $size_id, $brand_id, $supplier_id in your SQL statement but never set them anywhere..
Though if you say that the edit works the first time, I'm guessing you might not have posted all your code?
I have a function called add_item() which actually inserts values in a field item_name of temporary table called temp having fields temp_id and item_name. I have another table calleed item which consists of fields item_id, item_name, price. I have another table called quotation which consists of fields q_id, item_id,item_name,price.
Now I cant figure out how do i compare the item_name from temp to the field item_name from item. And then, insert the values of item in quotation table. Can anyone guide me please?
For example i have the following records in temp
temp_id item_name
1 kit
2 drill
3 tester
and i have the following records in item:
id item_name price
1 drill A 100
2 drill B 354
3 drill C 743
4 tester 643
5 cccc 643
What I want to do is compare the item_name from temp table with that of table item.
after comparing i should insert these values in table quotation
quotation_id searched_name item_name price
1 kit not found null
2 drill drill A 100
3 drill drill B 354
4 drill drill C 743
5 tester tester 643
Can someone please guide me where to start?Thanks
//select query for getting data from both tables
$get_data=mysql_query("SELECT *,temp.item_name AS searched, item.item_name AS response
FROM temp JOIN item ON temp.item_name = item.item_name");
while($datas=mysql_fetch_array($get_data))
{
//inserting into quotation table
mysql_query("INSERT INTO quotation SET
searched_name='".$datas['searched']."',
item_name='".$datas['response']."',
price='".$datas['price']."' ");
}
If you mean how to refer to fields in multiple tables/databases in a single query, you use the '.' notation:
SELECT table1.id, table2.value, table3.discount etc...
with the appropriate tables specified in your FROM and JOIN clauses. This can be extended to refer to fields in other databases entirely:
SELECT table1.id, table2.value
FROM database1.table1, database2.table2
update:
INSERT INTO quotations
SELECT item.item_name AS item_name, price
FROM records
LEFT JOIN temp ON item.item_name = temp.item_name;
should do the trick, assuming your quotations table has item_name and price fields. This will pull out any records where the item_Name is the same in both tables, and insert the item_name and price into quotations.