I'm having trouble understanding how to use a subquery to remove entries from a main query. I have two tables;
mysql> select userid, username, firstname, lastname from users_accounts where (userid = 7) or (userid = 8);
+--------+----------+-----------+----------+
| userid | username | firstname | lastname |
+--------+----------+-----------+----------+
| 7 | csmith | Chris | Smith |
| 8 | dsmith | Dan | Smith |
+--------+----------+-----------+----------+
2 rows in set (0.00 sec)
mysql> select * from users_contacts where (userid = 7) or (userid = 8);
+---------+--------+-----------+-----------+---------------------+
| tableid | userid | contactid | confirmed | timestamp |
+---------+--------+-----------+-----------+---------------------+
| 4 | 7 | 7 | 0 | 2013-10-03 12:34:24 |
| 6 | 8 | 8 | 0 | 2013-10-04 09:05:00 |
| 7 | 7 | 8 | 1 | 2013-10-04 09:08:20 |
+---------+--------+-----------+-----------+---------------------+
3 rows in set (0.00 sec)
What I would like to do is pull a list of contacts from the users_accounts table that will;
1) Omit the user's own account (in other words, I don't want to see my own name in the list).
2) See all contacts that have a "confirmed" state of "0", but
3) If the contact also happens to have a "confirmed" status of "1" (request sent) or "2" (request confirmed), do not include them in the results.
How can a sub-query be written to pull anything that turns up as a 1 or 2?
Subqueries at this point do not look necessary. You could join the tables like so:
select u.userid, u., firstname, u.lastname from users_accounts u join user_contacts c on u.userid = c.userid where u.userid != your_user_id and c.confirmed = 0;
in this generic example, your_user_id is obviously a placeholder for however you determine the current user's id.
but if you absolutely must use a subquery:
select userid, username, firstname, lastname from users_accounts where userid != your_user_id and userid not in (select userid from user_contacts where confirmed = 1 or confirmed = 2);
Related
I have this 2 tables
1st Table "Users"
+----+-----------+----------+
| ID | FirstName | LastName |
+----+-----------+----------+
| 1 | Jeff | Bezos |
| 2 | Bill | Gates |
| 3 | Elon | Musk |
+----+-----------+----------+
2nd Table "Records"
+----+--------+------------+
| ID | IDUser | RecordDate |
+----+--------+------------+
| 1 | 1 | 15/06/2021 |
| 2 | 2 | 05/06/2021 |
| 3 | 2 | 12/06/2021 |
| 4 | 2 | 02/06/2021 |
| 5 | 1 | 17/06/2021 |
+----+--------+------------+
So this 2 tables are linked each other by using a Foreing key Records.IDUsers -> Users.ID
I wanted to make a query that does this
+-----------+----------+----------------+--------------------+
| FirstName | LastName | Lastest Record | Numbers of Records |
+-----------+----------+----------------+--------------------+
| Jeff | Bezos | 17/06/2021 | 2 |
| Bill | Gates | 12/06/2021 | 3 |
| Elon | Musk | NULL | NULL |
+-----------+----------+----------------+--------------------+
You need to use LEFT JOIN in order to get back users without records too; then the MAX and COUNT aggregate functions.
First version: This will return 0 for the number of records instead of NULL, when there are no records for a specific user. Latest record will be NULL as expected.
SELECT
FirstName,
LastName,
MAX(RecordDate) AS LatestRecord,
COUNT(Records.ID) AS NumberOfRecords
FROM Users LEFT JOIN Records on Users.ID = Records.IDUser
GROUP BY Users.ID;
If you want NULL instead of 0 (which normally you do not want), you can use the IF function like this:
SELECT
FirstName,
LastName,
MAX(RecordDate) AS LatestRecord,
IF(COUNT(Records.ID) > 0, COUNT(Records.ID), NULL) AS NumberOfRecords
FROM Users LEFT JOIN Records on Users.ID = Records.IDUser
GROUP BY Users.ID;
Second version: It might happen that running the above query will return an error, something like:
Error: ER_WRONG_FIELD_WITH_GROUP: ...; this is incompatible with sql_mode=only_full_group_by
This happens when/if the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default since MySQL 5.7.5). In order to get around this error, you can use the ANY_VALUE function to select the nonaggregated fields:
SELECT
ANY_VALUE(FirstName) AS FirstName,
ANY_VALUE(LastName) AS LastName,
MAX(RecordDate) AS LatestRecord,
COUNT(Records.ID) AS NumberOfRecords
FROM Users LEFT JOIN Records on Users.ID = Records.IDUser
GROUP BY Users.ID;
left join select all user even if does not have records
select * from users left join records on records.IDUser = ID;
I'm trying write a query:
SELECT id FROM users WHERE status = 3
But if this sample returns an empty response, then I need instead to select the id where status = 4, and if it returns empty again, where status = 5.
How can I write a single query to solve this?
I think you simply want:
SELECT id
FROM users
WHERE status >= 3
ORDER BY status asc
LIMIT 1;
If you want multiple users:
SELECT u.id
FROM users u
WHERE u.status = (SELECT MIN(u2.status)
FROM users u2
WHERE u2.status >= 3
);
If you have a fixed list you want to test, you can also use:
select u.id
from users u
where u.status = 3
union all
select u.id
from users u
where u.status = 4 and
not exists (select 1 from users u2 where u2.status in (3))
union all
select u.id
from users u
where u.status = 5 and
not exists (select 1 from users u2 where u2.status in (3, 4));
You can use OR condition or use IN operator
SELECT id FROM users WHERE status = 3 or status = 3 or status = 5
or
SELECT id FROM users WHERE status IN (3,4,5)
I will use the case statement in the where clause:
select id
from users
where status = case when status = 3 and id is null then 4
when status = 4 and id is null then 5
else 3
end
Let me know if you have any question.
Assuming that your table look like this:
+----+--------+
| id | status |
+----+--------+
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 3 | 3 |
| 3 | 4 |
| 4 | 4 |
| 4 | 5 |
| 5 | 5 |
+----+--------+
And based on your condition where you want to see the lowest status first for each id, you can use MIN() operator.
So, from your original query:
SELECT id,MIN(status) FROM users GROUP BY id;
Then you'll get a result like this:
+----+-------------+
| id | MIN(status) |
+----+-------------+
| 1 | 3 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
+----+-------------+
These are two tables from a part of supposed Twitter like database where users can follow other users. The User.name field is unique.
mysql> select uID, name from User;
+-----+-------------------+
| uID | name |
+-----+-------------------+
| 1 | Alice |
| 2 | Bob |
| 5 | Iron Maiden |
| 4 | Judas Priest |
| 6 | Lesser Known Band |
| 3 | Metallica |
+-----+-------------------+
6 rows in set (0.00 sec)
mysql> select * from Follower;
+-----------+------------+
| subjectID | observerID |
+-----------+------------+
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 2 |
+-----------+------------+
7 rows in set (0.00 sec)
mysql> call newFollowSuggestionsForName('Bob');
+-------------------+
| name |
+-------------------+
| Lesser Known Band |
+-------------------+
1 row in set (0.00 sec)
I want to make an operation that will suggest for a user X a list of users they may be interested in following. I thought one heuristic could be to show X for all y who user y follows where X and y follow at least 3 of the same Users. Below is the SQL I came up with to do this. My question is if it could be done more efficiently or nicer in some other ways.
DELIMITER //
CREATE PROCEDURE newFollowSuggestionsForName(IN in_name CHAR(60))
BEGIN
DECLARE xuid INT;
SET xuid = (select uID from User where name=in_name);
select name
from User, (select subjectID
from follower
where observerID in (
select observerID
from Follower
where observerID<>xuid and subjectID in (select subjectID from Follower where observerID=xuid)
group by observerID
having count(*)>=3
)
) as T
where uID = T.subjectID and not exists (select * from Follower where subjectID=T.subjectID and observerID=xuid);
END //
DELIMITER ;
Consider the following refactored SQL code (untested without data) for use in stored procedure.
select u.`name`
from `User` u
inner join
(select subf.observerID, subf.subjectID
from follower subf
where subf.observerID <> xuid
) f
on u.UID = f.subjectID
inner join
(select f1.observerID
from follower f1
inner join follower f2
on f1.subjectID = f2.subjectID
and f1.observerID <> xuid
and f2.observerID = xuid
group by f1.observerID
having count(*) >= 3
) o
on f.observerID = o.observerID
I think the basic query starts as getting all "observers" who share three "subjects" with a given observer:
select f.observerid
from followers f join
followers f2
on f.subjectid = f2.subjectid and
f2.observerid = 2
group by f.observerid
having count(*) = 3;
The rest of the query is just joining in the names to fit into your paradigm of using names for references rather than ids.
Im struggling to articulate this, let alone execute in in MYSQL. How Do I return the userId X where userId.X and permissionId in (1,2,3,4,5,6,7,8) ?
The below example should return 6.
MariaDB [mailserver]> select * from user2permission;
+--------------+--------+
| permissionId | userId |
+--------------+--------+
| 1 | 5 |
| 1 | 6 |
| 2 | 6 |
| 2 | 7 |
| 3 | 6 |
| 4 | 6 |
| 5 | 6 |
| 6 | 6 |
| 7 | 6 |
| 8 | 6 |
+--------------+--------+
This kind of query can be written with the use of Group By clause and counting the instance as per the filteration applied in where clause
SELECT userId
FROM user2permission
WHERE permissionId IN (1,2,3,4,5,6,7,8)
GROUP BY userId
HAVING COUNT(*) = 8
You want to only show users that have an entry for all required permissions. Two solutions spring to mind:
select *
from users
where userid in (select userid from user2permission where permissionid = 1)
and userid in (select userid from user2permission where permissionid = 2)
...
and
select userid,
from user2permission
group by userid
having count(case when permissionid = 1 then 1 end) > 0
and count(case when permissionid = 2 then 1 end) > 0
...
And when I say "spring" to mind, I mean exactly that = without much thinking :-) Rizwan's aggregation solution is what you should use.
Let's say I have 2 tables.
The first table is a list of personas. A user can have many personas.
mysql> select id, user_id, name from personas_personas;
+----+---------+--------------+
| id | user_id | name |
+----+---------+--------------+
| 8 | 1 | startup |
| 9 | 1 | nerd |
| 10 | 1 | close |
| 12 | 2 | Nerd |
| 13 | 2 | Startup |
| 14 | 2 | Photographer |
+----+---------+--------------+
6 rows in set (0.00 sec)
Now, I have another table called "approvals".
mysql> select id, from_user_id, to_user_id, persona_id from friends_approvals;
+----+--------------+------------+------------+
| id | from_user_id | to_user_id | persona_id |
+----+--------------+------------+------------+
| 2 | 1 | 2 | 8 |
| 3 | 1 | 2 | 9 |
+----+--------------+------------+------------+
2 rows in set (0.00 sec)
If from_user wants to approve to_user to a persona, then a record is inserted.
I'm trying to do this query...
Given a user, find all its personas. Then, for each persona, determine if it's approved for a certain to_user. If so, return is_approved=1 in the result set. Otherwise, return is_approved=0 in the result set.
So this is where I start:
SELECT *
FROM personas_personas
WHERE user_id = 1
LEFT JOIN friends_approvals ON
...but i don't know where to go from here.
So, the final result set should have all the columns in the personas_personas table, and then also is_approved for each of the results.
SELECT
pp.*,
CASE
WHEN exists (
SELECT
*
FROM
friends_approvals fa
WHERE
fa.from_user_id = pp.user_id AND
fa.persona_id = pp.id AND
fa.to_user_id = 2
)
THEN 1
ELSE 0
END as is_approved
FROM
personas_personas pp
WHERE
pp.user_id=1
Or, depending on your taste:
SELECT
pp.*,
CASE
WHEN fa.from_user_id IS NOT NULL
THEN 1
ELSE 0
END as is_approved
FROM
personas_personas pp
LEFT OUTER JOIN friends_approvals fa ON
pp.user_id = fa.from_user_id AND
pp.id = fa.persona_id AND
fa.to_user_id = 2
WHERE
pp.user_id=1
If I'm understanding your needs correctly, you can do this:
SELECT personas_personas.*,
CASE WHEN friends_approvals IS NULL THEN 0 ELSE 1 END AS is_approved
FROM personas_personas
LEFT
OUTER
JOIN friends_approvals
ON friends_approvals.from_user_id = ...
AND friends_approvals.to_user_id = personas_personas.user_id
AND friends_approvals.persona_id = personas_personas.id
WHERE personas_personas.user_id = ...
;
That will find every personas_personas record with the specified user_id, together with an indicator of whether that user, in that persona, has been "approved" by a specified from_user_id.
(If that's not what you want, then please clarify!)