selecting "friends" with mySQL JOIN CASE - mysql

Here i posted a question about doing JOIN depending on the value of the column in the row.
You will need that is you make an Add Friend feature, where you write the ID of the 2 users who are Adding each other into user_1_id (my id) and user_2_id (friend id).
When you want to see who you are friends with, select DEPENDING on whether user_1_id or user_2_id has the ID of the surrent User (the one who is browsing)
I figured it out so down below is the query you want to use in case you need to do it.
Here is the query
$sql_inp = 'SELECT DISTINCT
users.id, users.first_name, users.last_name,
CASE
WHEN friends.user_2_id="'.$_SESSION[USER][id].'" //equal to current user id
THEN (SELECT friends.user_1_id FROM friends WHERE friends.user_2_id="'.$_SESSION[USER][id].'") // if user_2_id is My id, then fetch the other row
ELSE friends.user_2_id // obviously the opposite
END
FROM users
LEFT JOIN friends ON users.id= // this case is completely the same as one above
CASE
WHEN friends.user_2_id="'.$_SESSION[USER][id].'" THEN (SELECT friends.user_1_id FROM friends WHERE friends.user_2_id="'.$_SESSION[USER][id].'")
ELSE friends.user_2_id
END
WHERE friends.user_1_id="'.$_SESSION[USER][id].'" OR friends.user_2_id="'.$_SESSION[USER][id].'" // fetch the row where the either one of the values is equal to My id
';
Hope this helps if anyone had trouble

Personally, I hate using CASE statement. It makes queries look cluttered. Try using the IF function
$sql_inp = 'SELECT
table1.val1,table1.val2,
table2.val1,table2.val2,
IF(table3.val1="'.$user_id.'",table3.val1,
IF(table3.val2 ="'.$user_id.'",table3.val2,
IFNULL(table3.val2,-1))) users_fetch
FROM table1
INNER JOIN table2 ON table2.val1=table1.val1
LEFT JOIN table3 ON table2.val1=users_fetch';
In this query, if table3.val1 and table3.val2 <> $user_id, then users_fetch is -1.
Give it a Try !!!

Related

MySQL Select from table return all, plus one column with condition and another query

I'm pretty basic at MySQL queries. I work on a Laravel web app, at this point it comes to edit the User Role's part. I have a table that lists options for a user's role (called mst_level), and another table reflects the list of users who has that role (called mst_user_level). Been search this topic several times, but always found a different case.
mst_level
mst_user_level
Expected Output:
Select all levels for a spesific user_id, and return all columns
in mst_level + 1 column called "checked", with the
condition if the user has that role in mst_user_level, return true,
else return false.
This is what I already did, which I know it's wrong
select a.*, coalesce(true, false) as checked from my_db_name.mst_level a
inner join my_db_name.mst_user_status b on a.id = b.mst_level_id
where b.mst_user_id = '363fdeea-5330-490a-b4db-34e32a3526d6'
Anyone can help me out with this? So much Appreciated...
You can do it with EXISTS:
SELECT m.*,
EXISTS (
SELECT 1
FROM my_db_name.mst_user_status s
WHERE s.mst_level_id = m.id
AND s.mst_user_id = '363fdeea-5330-490a-b4db-34e32a3526d6'
) AS checked
FROM my_db_name.mst_level m;
Or with a LEFT JOIN where the conditions are set in the ON clause:
SELECT m.*, s.mst_level_id IS NOT NULL AS checked
FROM my_db_name.mst_level m LEFT JOIN my_db_name.mst_user_status s
ON s.mst_level_id = m.id AND s.mst_user_id = '363fdeea-5330-490a-b4db-34e32a3526d6';

SQL IF ELSE WITH MULTIPLE SELECT STATEMENT

I want to optimize these SQL queries using if-else but how I should use it? .
if this query result contain 'ALL'
SELECT
bdsubcategory.subcategoryID as ID,
bdsubcategory.subcategoryName as Name
FROM
phonebook.newsms_subscription
INNER JOIN bdsubcategory ON bdsubcategory.subcategoryID = newsms_subscription.subcategoryID
INNER JOIN newsms_client ON newsms_subscription.clientID =newsms_client.clientID
INNER JOIN newsms_person ON newsms_subscription.personID = newsms_person.personID
WHERE
newsms_subscription.isActive = 1 AND
newsms_person.personID = '856'
Then i want to query this
SELECT
bdsubcategory.subcategoryID as ID,
bdsubcategory.subcategoryName as Name
FROM
phonebook.newsms_subscription
INNER JOIN bdsubcategory ON bdsubcategory.subcategoryID = newsms_subscription.subcategoryID
INNER JOIN newsms_person ON newsms_subscription.personID = newsms_person.personID
WHERE
newsms_subscription.isActive = 1
GROUP BY subcategoryName
ORDER BY subcategoryName
otherwise take query1 result .
The problem is that if we do not refactor your project, then you always have to evaluate query1 and see whether it contains All or not. If it does not contain All, then you need to evaluate query2 as well. This can hardly be optimized, let's see a few approaches:
Quickening query1
Since All might be not be the very last evaluated element, adding it to the filter and limiting it is a good idea to quicken query1:
SELECT
COUNT(*)
FROM
phonebook.newsms_subscription
INNER JOIN bdsubcategory ON bdsubcategory.subcategoryID = newsms_subscription.subcategoryID
INNER JOIN newsms_client ON newsms_subscription.clientID =newsms_client.clientID
INNER JOIN newsms_person ON newsms_subscription.personID = newsms_person.personID
WHERE
newsms_subscription.isActive = 1 AND
newsms_person.personID = '856' AND
bdsubcategory.subcategoryName = 'ALL'
LIMIT 0, 1
So, you could create a stored procedure which evaluates query1' (query1' is the quickened version of query1, as seen above) and if there is a result, then we need to execute query1. Otherwise we need to execute query2. This way you still execute two queries, but the first query is optimized.
Refactoring
Note that the second query does not change. You could create a table where you could cache its results, using a periodic job. Then, you could skip the second table to
SELECT ID, Name
FROM MyNewTable;
without the many joins. You would also cache the results of the first query into a table where the items having ALL would be stored and query that table.
One option would be to use a CASE.
Change this:
newsms_person.personID = '856'
To this:
'Y' = CASE WHEN UPPER('856') = 'ALL' THEN 'Y'
WHEN newsms_person.personID = '856' THEN 'Y'
ELSE 'N' END
Alternatively, a stored procedure could be used to first validate whether the personID seems valid, then returns the appropriate data.

SQL Joining Diffrent Size Tables Together With Null Value Replacement

I am working on a query for a datatable and I can't seem to get it to display how I want, I don't know if this is even possible in SQL What I am looking to do is get a query to respond with ideally an extra column of Boolean type.
Currently I can run two queries and they both work perfectly but I can't work out how to join them together bellow is the code from my first query what this does is return beers a user has tried this works fine and as expected and returns as expected.
SELECT *
FROM keg.beer
JOIN keg.userbeer
ON beer.id = userbeer.beer_id
WHERE userbeer.username_id = 1;
The second query is even simpler and is just a select getting the list of beers.
SELECT * FROM keg.beer
What I want to do is run a query and have it return a list of beers with a Boolean value if the user has tried it or not.
You're not going to run into too many scenarios for "Desired Results" that can't be produced with plain 'ol SQL. In this case you'll use a CASE statement to determine if the person has tried a beer. You'll also want a LEFT OUTER JOIN so you don't drop records coming from your beer table when your filtered userid doesn't have a userbeer record for that beer:
SELECT
beer.name,
beer.id,
beer.country,
CASE WHEN userbeer.username_id IS NULL THEN 0 ELSE 1 END AS user_tried_beer_boolean
FROM keg.beer
LEFT OUTER JOIN keg.userbeer
ON beer.id = userbeer.beer_id
AND userbeer.username_id = 1;
As #SeanLange mentioned in the comments here, the restriction of the WHERE statement for the userid would cause records to be dropped that you want in your result set, so we move the restriction of username_id = 1 to the ON portion of the LEFT OUTER JOIN so that the userbeer table results are restricted to just that user before it's joined to the beer table.
Now I need a drink.
SELECT b.id,
b.name,
CASE WHEN u.username_id IS NOT NULL THEN TRUE ELSE FALSE END AS userdrankbeer
FROM keg.beer b
LEFT JOIN ( SELECT * FROM keg.userbeer WHERE username_id = 1 ) u
ON beer.id = userbeer.beer_id
;

Correlated Subquery in a MySQL CASE Statement

Here is a brief explanation of what I'm trying to accomplish; my query follows below.
There are 4 tables and 1 view which are relevant for this particular query (sorry the names look messy, but they follow a strict convention that would make sense if you saw the full list):
Performances may have many Performers, and those associations are stored in PPerformer. Fans can have favorites, which are stored in Favorite_Performer. The _UpcomingPerformances view contains all the information needed to display a user-friendly list of upcoming performances.
My goal is to select all the data from _UpcomingPerformances, then include one additional column that specifies whether the given Performance has a Performer which the Fan added as their favorite. This involves selecting the list of Performers associated with the Performance, and also the list of Performers who are in Favorite_Performer for that Fan, and intersecting the two arrays to determine if anything is in common.
When I execute the below query, I get the error #1054 - Unknown column 'up.pID' in 'where clause'. I suspect it's somehow related to a misuse of Correlated Subqueries but as far as I can tell what I'm doing should work. It works when I replace up.pID (in the WHERE clause of t2) with a hard-coded number, and yes, pID is an existing column of _UpcomingPerformances.
Thanks for any help you can provide.
SELECT
up.*,
CASE
WHEN EXISTS (
SELECT * FROM (
SELECT RID FROM Favorite_Performer
WHERE FanID = 107
) t1
INNER JOIN
(
SELECT r.ID as RID
FROM PPerformer pr
JOIN Performer r ON r.ID = pr.Performer_ID
WHERE pr.Performance_ID = up.pID
) t2
ON t1.RID = t2.RID
)
THEN "yes"
ELSE "no"
END as pText
FROM
_UpcomingPerformances up
The problem is scope related. The nested Selects make the up table invisible inside the internal select. Try this:
SELECT
up.*,
CASE
WHEN EXISTS (
SELECT *
FROM Favorite_Performer fp
JOIN Performer r ON fp.RID = r.ID
JOIN PPerformer pr ON r.ID = pr.Performer_ID
WHERE fp.FanID = 107
AND pr.Performance_ID = up.pID
)
THEN 'yes'
ELSE 'no'
END as pText
FROM
_UpcomingPerformances up

select values from multiple tables where value = X

I'm trying to perform what I assume is a very simple query on a MySQL DB. Here's my table setup;
Table 1 - CMS_AccessLevels
accessLevel
titleColor
Table 2 - CMS_Users
userID
username
userEmail
userAvatar
userSignature
accessLevel
I've already got this query;
SELECT `titleColor` FROM `CMS_AccessLevels` WHERE `accessLevel` = (SELECT `accessLevel` FROM `CMS_Users` WHERE `userID` = 3)
This works correctly and returns the correct titleColor value based on the accessLevel matching across both tables.
Now, what I want to do is also grab some of the values from CMS_Users as well. For the sake of simplicity, let's assume I want to grab only a few of the values, so my result set might look something like this;
userID|username|userAvatar|accessLevel|titleColor
-------------------------------------------------
0 |Scott |image.png | 6 |#FFFFFF
or as a PHP Array (shown just so you can see the logical layout if the above table didn't make sense);
array('userID' => $result['userID'],
'username' => $result['username'],
'userAvatar' => $result['userAvatar'],
'accessLevel' => $result['accessLevel'],
'titleColor' => $result['titleColor'];
Let's say I want to get userID, userName, userAvatar and accessLevel from CMS_Users, and titleColor from CMS_AccessLevels where CMS_Users.userID is equal to '3', remembering that CMS_AccessLevels.accessLevel and CMS_Users.accessLevel MUST match.
Realistically, the only piece of data I know before running the query is userID.
Is it possible to do this with a single query?
Try this:
SELECT u.userID, u.username, u.userAvatar, u.accessLevel, al.titleColor
FROM CMS_AccessLevels al
INNER JOIN CMS_Users u
ON u.accessLevel = al.accessLevel
WHERE u.userID = 3
You are using subqueries whereas joins will be the right choice. You might try something like
SELECT a.titleColor AS titleColor, u.username AS username FROM CMS_users u INNER JOIN CMS_AccessLevels a ON u.accessLevel = a.accessLevel WHERE u.userID = '3'