I have an extensive SQL SELECT That performs a calculation of TotalNetWorth for a number of Users. The result is the TotalNetworth and User. This can contain multiple records. Example:
-------------------------
|TotalNetWorth | UserId |
-------------------------
| 24.45 | 1 |
| 45.34 | 3 |
-------------------------
What I want to do is update the NetWorth column in my Users table with the TotalNetWorth value, and UserId = Users.Id as the key. What's the best way to go about this?
You can use a JOIN on an aliased subquery.
UPDATE
Users
FROM
Users u
INNER JOIN
(SELECT WhatEver FROM YourQueryThatCalcsNetWorth) nw
ON
nw.UserID = u.UserId
Something like that
UPDATE u
FROM Users u
JOIN tableTotalNetWorth t ON t.UserID = u.UserId
CREATE TEMPORARY TABLE TempNetWorth AS (SELECT * FROM [your query])
UPDATE Users u, TempNetWorth t
SET u.NetWorth = t.TotalNetWorth
WHERE u.UserID = t.UserId
do your select first and then update immediately with cte help
WITH cte_query AS (
SELECT TotalNetWorth = <calculate_total>
FROM [Users])
UPDATE cte_query
SET TotalNetWorth = TotalNetWorth;
You could do an INSERT .... SELECT .... ON DUPLICATE KEY UPDATE ...., as explained here.
You may have to use your extensive SELECT query to pull data into a temporary table first, say "temp" and then try using this query:
Update Users set NetWorth = (select TotalNetWorth from temp where Users.Id = temp.UserId)
Related
I have a table for users like this
id | name | password | email
1 saeid ***** asd#asd.com
I have another table called appointments
id | created_by | due_date | notification_send
1 1 ***** 0
I want to get all users from users table where they have at least created one appointment in the appointments table (denoted by created_by field in the appointments table).
I have tried the code below but it fails:
SELECT * FROM users LEFT JOIN appointments a ON persons.id = a.created_by
But obviously it does not work.
One way is to use the exists predicate:
SELECT * FROM users u
WHERE EXISTS (SELECT 1 FROM appointments a WHERE a.created_by = u.id)
Alternatively you could use an inner join, but the exists query corresponds better to your question in my opinion (that is if you only need data from the users table).
The left join says to get all rows from users regardless if they have matching rows in appointments which is not what you want.
You are searching for a match between the table and so I would suggest doing a INNER JOIN rather like below
SELECT * FROM users u
JOIN appointments a ON u.id = a.created_by
Also check your ON clause once I think either this is a typo or a big mistake. You are selecting from users table then why persons.id??
ON persons.id = a.created_by
Try something like this:
http://sqlfiddle.com/#!9/5eba3/2
select * from users c where (select count(*) from appointments where created_by = c.id) > 0;
I need help with a sql query.
I have these 2 tables:
player_locations:
ID | playerid | location <- unqiue key
---|-----------------------
1 | 1 | DOWNTOWN
and users:
ID | playername | [..]
----|--------------------
1 | example1 | ...
I need a select to get the users.playername from the player_locations.playerid. I have the unique location to get the player_locations.playerid.
Pseudo query:
SELECT playername
FROM users
WHERE id = player_locations.playerid
AND player_locations.location = "DOWNTOWN";
The output should be example1.
This is just a simple INNER JOIN. The general syntax for a JOIN is:
SELECT stuff
FROM table1
JOIN table2 ON table1.relatedColumn = table2.relatedColumn
In your case, you can relate the two tables using the id column from users and playerid column from player_locations. You can also include your 'DOWNTOWN' requirement in the JOIN statement. Try this:
SELECT u.playername
FROM users u
JOIN player_locations pl ON pl.playerid = u.id AND pl.location = 'DOWNTOWN';
EDIT
While I personally prefer the above syntax, I would like you to be aware of another way to write this which is similar to what you have now.
You can also select from multiple tables by using a comma in your FROM clause to separate them. Then, in your WHERE clause you can insert your conditions:
SELECT u.playername
FROM users u, player_locations pl
WHERE u.id = pl.playerid AND pl.location = 'DOWNTOWN';
Here is the solution.
SELECT
playername
FROM users
WHERE id = (SELECT id FROM player_locations WHERE location='DOWNTOWN')
I have a idea, try this:
SELECT playername
FROM users
WHERE id IN (SELECT DISTINCT playerid FROM player_location WHERE location LIKE "DOWNTOWN");
I'm trying to insert a row into mentions when a username exists in the users table.
INSERT INTO mentions (user_id)
SELECT USER_ID
FROM users
WHERE EXISTS (
SELECT USER_ID FROM users
WHERE USERNAME LIKE 'mike'
);
However, the above query is adding ALL user_ids into the mentions table -- all 1 million of them. What am I overlooking here?
Users table schema
USER_ID | USER_NAME | USER_STATUS
1 | mike | active
2 | brian | active
mentions table schema
MENTION_ID | COMMENT_ID | USER_ID
I have a comment "#mike have you talked to #john lately?" and I'm parsing for the mentions. If mike is found in the user's table, I want to insert it into the mentions table along with the comment_id.
exists needs to have a correlation to the outer select so something like this
INSERT INTO mentions (user_id)
SELECT u.user_id
FROM users u
WHERE EXISTS
( SELECT 1 FROM mentions m
WHERE u.user_id = m.user_id
AND m.username = 'mike'
);
you can also use IN
INSERT INTO mentions (user_id)
SELECT u.user_id
FROM users u
WHERE u.user_id IN
( SELECT m.user_id FROM mentions m
WHERE m.username = 'mike'
);
NOTE:
I removed the LIKE 'mike' and just changed it to = 'mike'... LIKE is used when you need to match partial strings... you can easily do it with = if you are looking for the whole string.
if you want to find a partial string then you should include wildcards like so LIKE "%mike%"
EDIT:
with your most recent edit you are trying to do a subquery when you dont need one.
INSERT INTO mentions (comment_id, user_id)
VALUES
(your_comment_id,(SELECT u.user_id FROM users uWHERE u.username = 'mike'));
However, it seems like you should have some sort of dependency between the tables.. can you post the table schemas?
Are you sure USERNAME is in the table mentions?
Maybe you just need:
INSERT INTO mentions (user_id)
SELECT USER_ID
FROM users
WHERE USERNAME LIKE 'mike'
I have a two simple tables
users
+----+--------+-----------+
| id | gender | birthdate |
+----+--------+-----------+
userpreference
+----+------------------+-----------------+
| id | preference value | preference type |
+----+------------------+-----------------+
Question:
I want to query all people who have not listed a specific preference value such as 'shopping'.This includes all people who have not listed any preference types as well so that column could be null, however since userpreference's column 'id' references users as a foreign key, I also want to include in my count all people who don't show up in the second table (user preference)?
Total # of people who do not have preference value 'shopping' as their preference value:
Here is what i have tried:
SELECT
(
SELECT COUNT(DISTINCT userpreference.id) FROM userpreference
WHERE preferencevalue != 'shopping')
+
(
SELECT COUNT(users.id)
FROM users
WHERE users.id NOT IN
(SELECT userpreference.Id
FROM userpreference )
)
AS'Total'
Select Count(*)
From Users
Where Not Exists (
Select 1
From UserPreference As UP1
Where UP1.id = Users.id
And UP1.PreferenceValue = 'Shopping'
)
Try a RIGHT JOIN, that will include all people who dont show up in the second table
SELECT *
FROM Users
RIGHT JOIN Userpreference ON ( users.userID = Users.userID)
WHERE preference_value = 'shopping'
Try this:
SELECT COUNT(DISTINT U.id) FROM users U NATURAL LEFT JOIN userpreference UP
WHERE UP.preferencevalue IS NULL OR UP.preferenceValue != 'shopping';
The LEFT JOIN should bring in all the users records whether or not they have a UP record.
I want to update all user records with the number of emails associated to that user. So I have
| userid | name | emailcount |
and
| userid | emaildata
I am trying to make a single UPDATE query which which will fill the emailcount with the number of emails that user has.
I have tried using a single UPDATE but can't make it work; do I need to use a subquery somehow to do this?
As Elliot suggests, you can drop the column emailcount and generate the value dynamically with a query like this:
select userid, name, coalesce(ec.count, 0) as emailcount
from User u
left outer join (
select userid, count(*) as count
from Email
group by userid
) ec on u.userid = ec.userid
If you want to do this action I suggest this query, but it is not tested on MySQL, I don't have the access at this moment. I hope that it is correct if not please others can correct me
UPDATE user SET emailcount = (SELECT count(*) FROM emaildata WHERE emaildata.userid user.userid)