I have two tables:
Persons (PersonID, LastName, FirstName)
Orders (O_Id, OrderNo, P_Id)
Orders.P_Id should have values from Persons.PersonID.
I am trying to do an insert on Orders to insert the P_Id into orders but I want it to match a value in my Persons table and also my Orders table so I can link them up and allow the P_id to be linked to the order.
I have tried this below? not sure what the best way to do this would be?
INSERT INTO Orders (P_Id)
SELECT PersonID FROM Persons
WHERE PersonID='1'
UNION ALL
SELECT O_Id FROM Orders
WHERE O_Id ='1';
Edit:
I have tried UNION ALL but it doesn't add them on the same line here is my sql fiddle which shows what is happening:
http://sqlfiddle.com/#!9/30a71/1
anyone help?
I think you want to UPDATE (not INSERT):
UPDATE ORDERS SET
P_Id = 1
WHERE O_Id = 1;
See SQLFiddle
I think what you're actually trying to achieve is not through the form of an INSERT, but an UPDATE:
Try this:
UPDATE Orders
SET P_ID = (SELECT PersonID From Persons WHERE PersonID = 1)
WHERE O_ID = 1
You can't "INSERT" a value into an existing row with a INSERT command. For that reason the UPDATE command exists.
The INSERT is useful only when creating a row in the table. For all other scenarios, when you are trying to populate a column with data, into an existing row, then you should use UPDATE.
The above query is basically a re-write of what you have, but since you already know the value of PersonID which you want to populate the P_ID column with, then you can simplify the query to:
UPDATE Orders
SET P_Id = 1
WHERE O_Id = 1
Related
I have the following table student which allows duplicate id's as shown below:
Table with duplicate Id's.
Now in this table I need to delete all other duplicate record and leaving any one of the unique record of the id.
i.e for example if execute the delete statement 7 records should be deleted leaving 2 records one with id as '1' and another with id as '2'.
As shown in below diagram:-
[Final Expected output][2]
How can i write a single SQL query to get above result.
Below is the sample sql query I am trying which is throwing compile time error
in sql editor as "unexpected student identifier".
DELETE FROM student as a
WHERE a.sno not in(select b.sno from test.student as b group by b.id);
Kindly help me to figure out my mistake in query.
thanks in advance.
[2]: https://i.stack.imgur.com/Z7tDc.png
You can delete it by using your UNIQUE KEY: SNO. It is used to uniquely identify the record for delete action.
delete a.*
from student a
where a.sno not in (
select sno from (
select min(sno) as sno
from student
group by id) tab
);
Try this:
set sql_safe_updates = 0;
DELETE FROM student
WHERE sno NOT IN (
SELECT b.sno FROM (SELECT MIN(a.sno) AS sno
FROM student a GROUP BY a.id) b);
set sql_safe_updates = 1;
The min() function indicates which row to keep from among the
duplicates
The nested subquery is to stop the the 'you can't specify target
table ... for update in FROM clause' msg.
The set_sql_safe_updates turns off error code 1175
delete from student where sno
not in( select st.* from (SELECT sno FROM student group by id) st);
Your query is partially correct...but when you did group by id you have to again take those ids here I took in 'st'.so that all ids are in 'st' and the query will become like
delete from student where sno
not in(1,6)
My database structure is:
items (id, item_name)
user (id, username)
inventory(id, user_id FK, item_id FK, amount)
I have a select query which returns rows with (item_id, amount)
I just want to add values from that select query into that inventory table.
So what i need in pseudo code is:
FUNCTION give_items(IN in_user_id)
FOR EACH ROW FROM THAT SELECT:
IF ROW EXISTS with user_id = in_user_id AND item_id = SELECT.item_id THEN INSERT ROW
ELSE UPDATE ROW amount = amount + SELECT.amount
it is like INSERT INTO SELECT ... ON DUPLICATE KEY, but i need to respect user_id and item_id not PRIMARY KEY
#EDIT
This is what i got now:
INSERT INTO `items_inventory` (`user_id`,`item_id`,`amount`)
SELECT mu.user_id, mi.item_id, SUM(mu.amount*mi.income) as amount_sum
FROM `mining_machines_users` AS mu
LEFT JOIN `mining_machines_income` AS mi ON mu.machine_id=mi.machine_id
WHERE mu.user_id=in_user_id
GROUP BY mi.item_id
ON mu.user_id=in_user_id AND mi.item_id=VALUES(`item_id`) //NEED FIX
`amount`=`amount`+VALUES(`amount`)
Sorry for my bad English, i hope that you will help me :)
Is the id property necessary? otherwise its maybe easier if you make a combined primary key of user_id and item_id
I have 2 tables :
Book(Name,quantity,supplier)
SuppliedBy (supplier,quantity)
I want the quantity in SuppliedBy table equal sum of the books supplied by that supplier, so I wrote a set statement
update supplier
set supplier.quantity = (select quantity
from (select sum(quantity) as quantity, SuppliedBy
from book group by SuppliedBy) a
where a.SuppliedBy = supplier.SuppliedBy)
However I want to automatically update quantity value in SuppliedBy when a new book is add. Please help
I think you need to create a after insert trigger on Book table to update value in supliedBy table.
How can I use a single query for inserting table when a column value is not found.
eg/ i want to insert new user only when this username not found
what i doing now is issue 1 query to check for existing,
then another query if no existing found. total 2 query
INSERT INTO friends (memberID) SELECT 1 WHERE NOT EXISTS (SELECT memberID FROM friends WHERE memberID = 1)
You just need to add FROM DUAL
INSERT INTO friends
(memberid)
SELECT 1
FROM dual
WHERE NOT EXISTS (SELECT memberid
FROM friends
WHERE memberid = 1)
sql fiddle
How about this:
INSERT INTO YourTable (UserName)
SELECT x
FROM (SELECT 'New User Name' AS x) a
WHERE x NOT IN(SELECT UserName
FROM YourTable)
Since you only want one row with a given value you should enforce that with a UNIQUE constraint on the table, for example:
ALTER TABLE friends ADD UNIQUE (memberID);
After you do that, you can simply add the IGNORE keyword to your insert statements and it won't report an error and it won't insert a duplicate row if it already exists.
INSERT IGNORE INTO friends(memberID) VALUES(1);
Say I have two tables: orderinfo and customerinfo
They look like this:
orderinfo:
OrderID
CustomerID
OrderCustomerName
OrderCustomerAddress
customerinfo:
CustomerID
CustomerName
CustomerAddress
Both OrderID and CustomerID are unique. When an order is to be created, I need to copy the info from customerinfo to orderinfo at that time as the customer may change his information later.
I hope I can just use CustomerID to achieve this. How should I write the subquery? Thanks.
When you insert a new order, you can grab a "snapshot" of the customer data with the following simple INSERT... SELECT query syntax:
INSERT INTO orderinfo (CustomerID, OrderCustomerName, OrderCustomerAddress, status)
SELECT CustomerID, CustomerName, CustomerAddress, 'P'
FROM customerinfo
WHERE CustomerID = <customerid here>
This inserts a new order with the customer info at the exact time the order was placed.
This information will remain just as how it was inserted even if the customer updates his or her information in the customerinfo table because there aren't any cascade effects other than if the CustomerID changes (which it shouldn't, and even if it did change, it wouldn't change the "snapshot" data).
To update orderinfo with the current values for customer name and address based on a CustomerID, use an UPDATE JOIN:
UPDATE
orderinfo
JOIN customerinfo ON orderinfo.CustomerID = customerinfo.CustomerID
SET
OrderCustomerName = CustomerName,
OrderCustomerAddress = CustomerAddress
WHERE OrderID = <some_order_id>
This is useful if you want to "freeze" the customer information associated with a specific order, even if the customer later changes that information globally. If I understand correctly, that is your intent.
You can also do this with an AFTER INSERT trigger on the orderinfo table. Then you needn't execute a separate query:
CREATE TRIGGER update_order_cust_info AFTER INSERT ON orderinfo
FOR EACH ROW
BEGIN
UPDATE
orderinfo
JOIN customerinfo ON orderinfo.CustomerID = customerinfo.CustomerID
SET
NEW.OrderCustomerName = CustomerName,
NEW.OrderCustomerAddress = CustomerAddress
WHERE OrderID = NEW.OrderID
END
What you are looking for is
INSERT INTO orderinfo
(OrderID, CustomerID, OrderCustomerName, OrderCustomerAddress)
VALUES (
'12345',
'789',
(SELECT CustomerName FROM customerinfo WHERE CustomerID = '789'),
(SELECT CustomerAddress FROM customerinfo WHERE CustomerID = '789')
)
But i strongly advise a change in your database structure. What you try to do violates the Database Normalisation rules. Instead, read this article on Wikipedia on Slowly Changing Dimensions and implement it as such.