SQL insert both specified and selected values - mysql

I have two tables shown below:
TableOwner:
UserID Name Initials
1 Peter Pet1
2 Mary Mar1
3 Petra Pet2
TableAsset
AssetID AssetName OwnerUserID
1 Samsung 3
2 Apple 1
3 Huawei 2
Now I want to insert into TableAsset these records:
AssetID AssetName OwnerUserID
4 Doro 2
5 Sony 1
How to use insert query and select query in one step?

You can do something like this in a single query. Passing the parameter will depend on you how you do it.
insert into TableAsset(AssetName, OwnerUserID)
select 'Doro', (select UserID from TableOwner where Initials = 'Mar1')
union all
select 'Sony', (select UserID from TableOwner where Initials = 'Pet1');

THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION.
You can look them up:
insert into tableAsset(AssetName, OwnerUserID)
select #AssetName, o.UserId
from tableOwner o
where o.initials = #Initials;
This basic structure will work for any database, although the method for passing parameters may differ among databases.

Related

Selecting a row with the same ID when the values of the second column are known

He's a beginner, and I've encountered this programming conundrum:
We have sample records in the table:
ID
VALUE
1
5
1
4
2
3
2
4
3
3
3
5
I would like to retrieve records with VALUE (3,4) values with the same ID, so as a result I would like to get ID 2
How to write such a mysql query to the database?
You can use HAVING.
SELECT id FROM table_name WHERE value IN (3, 4) GROUP BY id HAVING COUNT(*) = 2;
I have prepared an example for you to see how you work.

Insert record and increment values of other records

I have a table with a custom sort order column.
ID NAME ORDER
1 Jack 4
2 Jill 2
3 Mike 5
4 Mark 1
5 Bill 3
I would like to insert a new record with an ID of 6, a NAME of Jane, and an ORDER of 3. I would like to insert it such that the old records are incremented to make room for the new record, resulting in something like this:
ID NAME ORDER
1 Jack 5
2 Jill 2
3 Mike 6
4 Mark 1
5 Bill 4
6 Jane 3
Can this be done using a SQL script? I was looking at this answer, but I'm not sure it can be made to work in my case. Plus it requires an extra table to temporarily hold values, which I would like to avoid.
Thanks.
[edit]
I forgot to add that there is a unique constraint non the third column. Though I understand there are ways of getting around this.
You can do this with two queries:
update mytable set order = order + 1 where order >= 3;
insert into mytable(id, name, order) values(6, 'Jane', 3);
Note, however, that this create a race condition, and might not behave properly under concurency stress.
A better solution would be not to store the customer ordering, but compute it on the fly in your queries (you can create a view to make it easier). For this, you would need to describe the logic behind the ordering.
Try this
INSERT INTO mytable(id, name, order) values (6, 'Jane', 0);
UPDATE mytable SET order = CASE WHEN id % 2 <> 0 THEN order + 1 ELSE order / 2;

Get data from table with id from another table

i have two Tables users_data and users_statistics
users_data:
id money position uid
1 1000 20921 3
2 3000 8742 0
3 2000 23214 3
users_statistics:
id lastname lastlogin
1 Hans 13.05.2200
2 Uwe 10.03.1900
3 Herbert 13.42.2421
Now, i want to SELECT all lastname WHERE uid = 3
My try was
SELECT `lastname` FROM users_statistics
JOIN users_data USING (id)
WHERE `uid` = 3
With this Query he returns me all 3 Rows, but why?
In the second row the uid is 0...
I hop someone can help, thanks in advance.
Sounds weird but now it works...
I only changed the uid to users_data.uid
SELECT `lastname` FROM users_statistics
JOIN users_data USING (id)
WHERE users_data.uid = 3
Now he only gives me the two rows with uid = 3
When someone can explain this, let me know it :D
your query works for me:
http://sqlfiddle.com/#!9/c5025/1
Also tested under local MySQL 5.5.38

MySQL subquery overview

Alright I am guessing I need a subquery to solve this and I am little rusty on these. So I have 3 tables:
tblAccount - Has User information and AccountID
tblItem - Has Item information and ItemID
tblAccountItem - Has 3 fields - AccountItemID / AccountID / ItemID
An account can have many items and an item can have many accounts. Example data:
tblAccount
AccountID AccountName AccountEmail
1 John Smith john#smith.com
2 Fred John fred#john.com
3 George Mike george#mike.com
tblItem
ItemID ItemName ItemDescription
1 Hammer Smashes things
2 Axe Breaks things
Ok so lets say the Hammer belongs to John,Fred and George. Axe only belongs to John and Fred.
tblAccountItem
AccountItemID AccountID ItemID
1 1 1
2 2 1
3 3 1
4 1 2
5 2 2
So I want to show what items John has and also show who else owns that item. The output I want to show is:
ItemName ItemDescription OtherOwners
Hammer Smashes things Fred, George
Axe Breaks things Fred
Any help would be greatly appreciated!
The answer by ctrahey is perfect but I have a slight condition to add. There are 2 types of accounts in tblAccount denoted by a field.
tblAccount
AccountID AccountName AccountEmail AccountDescription AccountTypeID
1 John Smith john#smith.com NULL 1
2 Fred John fred#john.com NULL 1
3 George Mike george#mike.com Runner 2
tblAccountTypeID
AccountTypeID AccountType
1 User
2 Admin
If the AccountTypeID is 1 then I need to output the AccountEmail. If the AccountTypeID is 2 I need to output the AccountDescription. Eg output (same story as above):
ItemName ItemDescription OtherOwners
Hammer Smashes things Fred, Runner
Axe Breaks things Fred
Going off the query that ctrahey I am guessing there needs to be an ALIAS field created. Something like:
WHERE AccountTypeID = 1 (SELECT AccountName)
WHERE AccountTypeID = 2 (SELECT AccountDescription)
I hope this makes sense, thanks for all the help so far!
Subqueries are very rarely actually needed, and are often replaced (with improved performance) by a well-designed JOIN.
Here, we start with AccountItem table (the WHERE clause immediately limits the query to only items owned by our account of interest); then we join the same table (aliasing it to 'others_items_join'), telling it to join with the same itemID but not owned by our account if interest. That's the essence of the entire query, the next two joins are only to bring in the actual strings we want to be in our output (the other people's names and the item names/descriptions). GROUP BY is used to give just one row per item which our account of interest has.
SELECT
ItemName,
ItemDescription,
GROUP_CONCAT(others.AccountName) as OtherOwners
FROM
tblAccountItem as my_items
LEFT JOIN tblAccountItem as others_items_join
ON others_items_join.ItemID = my_items.ItemID AND others_items_join.AccountID != ?
LEFT JOIN tblAccount as others
ON others_items_join.AccountID = others.AccountID
JOIN tblItems ON my_items.ItemID = tblItems.ItemID
WHERE my_items.AccountID = ?
GROUP BY ItemName
You better use a coding to resole this , here rough query that's may helps you get an idea :
SELECT AccountName
FROM tblAccount
WHERE AccountID = (SELECT AccoundID
FROM tblAccountItem
WHERE itemID = (SELECT itemID
FROM tblAccountItem
WHERE AccountID = 1 (john Id as example)));
Hope this helps
SELECT ItemName, ItemDescription, AccountItemID FROM tblitem RIGHT JOIN tblaccountitem ON tblitem.ItemID=tblaccountitem.ItemID
I hope this helps lead to your answer. I am still looking into this

MySql : UNION is not getting executed when executed as a view

I am trying to create a view for a UNION of 2 select statements that I have created.
The UNION is working fine when executed individually
But the problem is only the 1st part of the UNION is getting executed when I am executing it as a view.
The query I am using is as below
SELECT DISTINCT products.pid AS id,
products.pname AS name,
products.p_desc AS description,
products.p_uid AS userid,
products.p_loc AS location,
products.isaproduct AS whatisit
FROM products
UNION
SELECT DISTINCT services.s_id AS id,
services.s_name AS name,
services.s_desc AS description,
services.s_uid AS userid,
services.s_location AS location,
services.isaservice AS whatisit
FROM services
WHERE services.s_name
The above works fine when i execute it separately. But when I use it as a view, it does not give me the results of the services part.
Could someone please help me with this?
If you could give the result set for each individual query above and then also give the result set for the UNION query, we could probably provide a better answer to your question. My gut reaction is that the second query may be returning a duplicate value, and since you are using UNION, duplicates are being removed. If you used UNION ALL, then all duplicate rows would be returned. For example, if the first query returned the row:
1 name1 description1 10 Home Y
2 name2 description2 20 Work Y
and the second row returned:
1 name1 description1 10 Home Y
The resulting output would be:
1 name1 description1 10 Home Y
2 name2 description2 20 Work Y
If you want all of the rows returned:
1 name1 description1 10 Home Y
2 name2 description2 20 Work Y
1 name1 description1 10 Home Y
Then you would use a UNION ALL instead of a UNION statement.
i think your fields userid and location are swapped in the two selects from the union, if of diferent data types, you will get an error, if not, you will get wrong results...is that it?