SQL SELECT name by id - mysql

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");

Related

Select users from table foreach repeated id

I have this table:
users
id | name
---------------------
1 | Lisa
2 | John
and i have this users list:
(1,2,2,2,1,2)
and i want to get this result:
Lisa,John,John,John,Lisa,John
how i can get this result just using SQL query in my Phpmyadmin without using PHP?
i must use Left Join ?
(Assuming orders table is on the same server) You should use inner join here. Because, there should be an user to have an entry in orders table.
SELECT abc = STUFF(( Select user.user_name + ',' from
orders inner join users on users.id = orders.user_id where orders.user_id in (your string of user ids) for
xml_path(' ')), 1, 1, '') FROM temp1

SQL retrieve joined data an array

I have the following database structure:
users:
id
name
user_activities:
user_id
activity_id
activities:
id
name
I'm trying to write a Select query that will output the following:
- user1.id, activities: {[activity.id, activity.name], ['activity.id, activity.name]};
- user2.id, activities: {[activity.id, activity.name], ['activity.id, activity.name]};
I know how to do it in two steps, but I have many users and selecting activities for each one is heavy. Is there way to do it with one MySQL query?
Solution using GROUP_CONCAT function with SEPARATOR option, which lets you get all activities for a certain user:
SELECT u.id, GROUP_CONCAT( a.id, "|", a.name
SEPARATOR ', ' ) AS useractivities
FROM `users` u
INNER JOIN `user_activities` ua ON u.id = ua.user_id
INNER JOIN `activities` a ON a.id = ua.activity_id
GROUP BY u.id
This query will return a resultset in such state:
id | useractivities
------------------------------------
79 | 17|sport
18 | 3|music, 19|outing, 17|sport
.. | ....
Then, while fetching each row from resultset you can easily explode(split) the useractivities field value by comma(as delimiter) and thus, get all activities for a certain user

mysql - selecting groups and users all in same query

I have following two tables 'USERS' and 'GROUPS':
USERS
-id
-name
-groupid
GROUP
-id
-name
I'd like to return all users along with their group's name and group id. It should be an outer join on group id field correct?
A simple INNER JOIN should be enough:
SELECT `USERS`.*, `GROUP`.name AS group_name
FROM `USERS`, `GROUP`
WHERE `USERS`.groupid = `GROUP`.id
You're going to want to look at the JOIN statement
Doing this from my phone, so pardon any moderately incorrect syntax, but something a long the lines of
Edit: other guy's syntax is better. It's too early here
You can use a LEFT JOIN between users and groups so that users who are not in a group still show up in the result set, but with group name and id NULL:
SELECT
a.*,
b.name AS group_name
FROM
users a
LEFT JOIN
`group` b ON a.group_id = b.id
Side note: Ensure that you're encasing the table name group in backticks because it is a reserved keyword.
The result-set should look something like:
id | name | group_id | group_name
-----------------------------------------------------------------------------
1 | John | 5 | ThisIsGroup5
3 | Tim | 3 | ThisIsGroup3
6 | NotInGroup | NULL | NULL
Changing LEFT to INNER in the above query would INNER JOIN the two tables and exclude the user "NotInGroup" from the result-set.

SQL Update with results of SELECT

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)

Counting records from table that appear is one but not other: MYSQL

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.