SQL finding members who are not friends of another member - mysql

I'm struggling to find a query which will return members who aren't friends of a certain member. Here is the layout of my tables:
member_login:
MemberID, email, password
member_info:
memberID, first_name, last_name
member_friends:
friendID, req_member, req_date, app_member, app_date, date_deactivated
I tried to use NOT IN to run a query that would return the opposite of friends but nothing I try seems to be working. Here's what I thought would work:
SELECT Mi.First_Name, Mi.Last_Name
FROM Member_Info Mi
WHERE Mi.Memberid NOT IN(
SELECT Mi.Memberid, Mi.First_Name, Mi.Last_Name
FROM Member_Info Mi, Member_Login Ml, Member_Friends Mf
WHERE Mi.Memberid = Ml.Memberid
AND (Mi.Memberid = Mf.Req_Member
AND Mf.App_Member = 1
OR Mi.Memberid = Mf.App_Member
AND Mf.Req_Member =1)
AND Ml.Date_Deactivated <= 0
AND Mf.App_Date > 0
);
Any ideas?

#Thedirktastik, please check the correct use of IN clause. Here in the MSDN you can take a look.
In you WHERE clause you are using IN so the subquery returning the values should return only Mi.Memberid column values. And your query is returning several different columns. Should be something like:
....
WHERE Mi.Memberid NOT IN(
SELECT Mi.Memberid
FROM....

what if you try
SELECT Mi.First_Name, Mi.Last_Name
FROM Member_Info Mi
WHERE Mi.Memberid NOT IN(
SELECT Mi.Memberid
FROM Member_Info Mi, Member_Login Ml, Member_Friends
WHERE Mi.Memberid = Ml.Memberid
AND (Mi.Memberid = Mf.Req_Member
AND Mf.App_Member = 1
OR Mi.Memberid = Mf.App_Member
AND Mf.Req_Member =1)
AND Ml.Date_Deactivated <= 0
AND Mf.App_Date > 0
);
because you are returning three values in your NOT IN ( ... ) when it should be one
SELECT Mi.Memberid, Mi.First_Name, Mi.Last_Name
should be
SELECT Mi.Memberid
you might get another error about your FROM statement as you will need to join to tables together to compare values but your friend table does not have any matching values so this could be a problem (poor design)
EDIT: database designs
A lot of this comes down to experience really but there are a few good books which you can check out like Head First SQL and Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback), these are great books to learn the basics and basic design, i recommend you check them out

This is a really bad design, and probably the reason for the down votes. I would look into making the member_friends table an intersect table (junction table). It will make your design, and therefore queries, much easier to use and understand.

Related

SQL query optimization taking lot of time in execution

We have two tables one is properties and another one is property meta when we are getting data from one table "properties" , query only take less then one second in execution but when we are use join to get the data using bellow query from both tables its taking more then 5 second to fetch the data although we have only 12000 record in the tables , i think there is an issue in the sql query any help or suggestion will be appreciated.
SELECT
u.id,
u.property_title,
u.description,
u.city,
u.area,
u.address,
u.slug,
u.latitude,
u.longitude,
u.sync_time,
u.add_date,
u.is_featured,
u.pre_construction,
u.move_in_date,
u.property_status,
u.sale_price,
u.mls_number,
u.bedrooms,
u.bathrooms,
u.kitchens,
u.sub_area,
u.property_type,
u.main_image,
u.area_size as land_area,
pm7.meta_value as company_name,
pm8.meta_value as virtual_tour,
u.year_built,
u.garages
FROM
tbl_properties u
LEFT JOIN tbl_property_meta pm7
ON u.id = pm7.property_id
LEFT JOIN tbl_property_meta pm8
ON u.id = pm8.property_id
WHERE
u.status = 1
AND (pm7.meta_key = 'company_name')
AND (pm8.meta_key = 'virtual_tour')
AND (
(
( u.city = 'Delta'
OR u.post_code LIKE '%Delta%'
OR u.sub_area LIKE '%Delta%'
OR u.state LIKE '%Delta%')
AND country = 'Canada'
)
OR (
( u.city = 'Metro Vancouver Regional District'
OR u.post_code LIKE '%Metro Vancouver Regional District%'
OR u.sub_area LIKE '%Metro Vancouver Regional District%'
OR u.state LIKE '%Metro Vancouver Regional District%' )
AND country = 'Canada'
)
)
AND
u.pre_construction ='0'
GROUP BY
u.id
ORDER BY
u.is_featured DESC,
u.add_date DESC
Try adding this compound index:
ALTER TABLE tbl_property_meta ADD INDEX id_key (property_id, meta_key);
If it doesn't help make things faster, try this one.
ALTER TABLE tbl_property_meta ADD INDEX key_id (meta_key, property_id);
And, you should know that column LIKE '%somevalue' (with a leading %) is a notorious performance antipattern, resistant to optimization via indexes. (There's a way to create indexes for that shape of filter in PostgreSQL, but not in MariaDB / MySQL.)
Add another column with the meta stuff; throw city, post_code, sub_area, and state and probably some other things into it. Then build a FULLTEXT index on that column. Then use MATCH(..) AGAINST("Delta Metro Vancouver Regional District") in the WHERE clause _instead of the LEFT JOINs (which are actually INNER JOINs) and the really messy part of the WHERE clause.
Also, the GROUP BY is probably unnecessary, thereby eliminating extra sort on the intermediate set of rows.

MySQL multiple joins and count distinct

I need to write query that joins several tables and I need distinct value from one table based on max count().
These are my tables names and columns:
bands:
db|name|
releases_artists:
release_db|band_db
releases_styles
release_db|style
Relations between tables are (needed for JOINs):
releases_artists.band_db = bands.db
releases_styles.release_db = releases_artists.release_db
And now the query that I need to write:
SELECT b.name, most_common_style
LEFT JOIN releases_artists ra ON ra.band_db = b.db
and here I need to find the most common style from all band releases
JOIN(
SELECT DISTINCT style WHERE releases_styles.release_db = ra.release_db ORDER BY COUNT() DESC LIMIT 1
)
FROM bands b
WHERE b.name LIKE 'something'
This is just a non working example of what I want to accomplish. It would be great if someone could help me build this query.
Thanks in advance.
EDIT 1
Each artist from table bands can have multiple records from releases_artists table based on band_db and each release can have multiple styles from releases_styles based on release_db
So if I search for b.name LIKE '%ray%' it returns something similar to:
`bands`:
o7te|Ray Wilson
9i84|Ray Parkey Jr.
`releases_artists` for Ray Wilson:
tv5c|o7te (for example album `Change`)
78wz|o7te (`The Next Best Thing`)
nz7c|o7te (`Propaganda Man`)
`releases_styles`
tv5c|Pop
tv5c|Rock
tv5c|Alternative Pop/Rock
----
78wz|Rock
78wz|Pop
78wz|Classic Rock
I need style name that repeats mostly from all artist releases as this artist main style.
Ok, this is a bit of a hack. But the only alternatives I could think of involve heaps of nested subqueries. So here goes:
SELECT name
, SUBSTRING_INDEX(GROUP_CONCAT(style ORDER BY release_count DESC SEPARATOR '|'), '|', 1) AS most_common_style
FROM (
SELECT b.db
, b.name
, rs.style
, COUNT(*) AS release_count
FROM bands b
JOIN releases_artists ra ON ra.band_db = b.db
JOIN releases_styles rs ON rs.release_db = ra.release_db
GROUP BY b.db, rs.style
) s
GROUP BY db;

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

Sql Result IN a Query

dont blame for the database design.I am not its database architect. I am the one who has to use it in current situation
I hope this will be understandable.
I have 3 tables containing following data with no foreign key relationship b/w them:
groups
groupId groupName
1 Admin
2 Editor
3 Subscriber
preveleges
groupId roles
1 1,2
2 2,3
3 1
roles
roleId roleTitle
1 add
2 edit
Query:
SELECT roles
from groups
LEFT JOIN preveleges ON (groups.groupId=preveleges.groupId)
returns specific result i.e roles.
Problem: I wanted to show roleTitle instead of roles in the above query.
I am confused how to relate table roles with this query and returns required result
I know it is feasible with coding but i want in SQL.Any suggestion will be appreciated.
SELECT g.groupName,
GROUP_CONCAT(r.roleTitle
ORDER BY FIND_IN_SET(r.roleId, p.roles))
AS RoleTitles
FROM groups AS g
LEFT JOIN preveleges AS p
ON g.groupId = p.groupId
LEFT JOIN roles AS r
ON FIND_IN_SET(r.roleId, p.roles)
GROUP BY g.groupName ;
Tested at: SQL-FIDDLE
I would change the data structure it self. Since It's not normalised, there are multiple elements in a single column.
But it is possible with SQL, if for some (valid) reason you can't change the DB.
A simple "static" solution:
SELECT REPLACE(REPLACE(roles, '1', 'add'), '2', 'edit') from groups
LEFT JOIN preveleges ON(groups.groupId=preveleges.groupId)
A more complex but still ugly solution:
CREATE FUNCTION ReplaceRoleIDWithName (#StringIds VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE #RoleNames VARCHAR(50)
SET #RoleNames = #StringIds
SELECT #RoleNames = REPLACE(#RoleNames, CAST(RoleId AS VARCHAR(50)), roleTitle)
FROM roles
RETURN #RoleNames
END
And then use the function in the query
SELECT ReplaceRoleIDWithName(roles) from groups
LEFT JOIN preveleges ON(groups.groupId=preveleges.groupId)
It is possible without function, but this is more readable. Made without editor so it's not tested in anyway.
You also tagged the question with PostgreSQL and it's actually quite easy with Postgres to work around this broken design:
SELECT grp.groupname, r.roletitle
FROM groups grp
join (
select groupid, cast(regexp_split_to_table(roles, ',') as integer) as role_id
from privileges
) as privs on privs.groupid = grp.groupid
join roles r on r.roleid = privs.role_id;
SQLFiddle: http://sqlfiddle.com/#!12/5e87b/1
(Note that I changed the incorrectly spelled name preveleges to the correct spelling privileges)
But you should really, really re-design your data model!
Fixing your design also enables you to define foreign key constraints and validate the input. In your current model, the application would probably break (just as my query would), if someone inserted the value 'one,two,three' into the roles table.
Edit
To complete the picture, using Postgres's array handling the above could be slightly simplified using a similar approach as MySQL's find_in_set()
select grp.groupname, r.roletitle
from groups grp
join privileges privs on grp.groupid = privs.groupid
join roles r on r.roleid::text = any (string_to_array(privs.roles, ','))
In both cases if all role titles should be shown as a comma separated list, the string_agg() function could be used (which is equivalent to MySQL's group_concat()
select grp.groupname, string_agg(r.roletitle, ',')
from groups grp
join privileges privs on grp.groupid = privs.groupid
join roles r on r.roleid::text = any (string_to_array(privs.roles, ','))
group by grp.groupname

MYSQL and IN in requests

I am a beginner when it comes to using mysql queries embedded inside other mysql queries using the IN statement.
I currently have this query:
SELECT DISTINCT BorName
FROM Borrower
WHERE BorId IN (
SELECT Borrower.BorId
FROM Loan
WHERE Loan.BcId IN (
SELECT BookCopy.BcId
FROM BookCopy
WHERE BookCopy.BtId In (
SELECT BookTitle.BtId
FROM BookTitle
WHERE BookTitle.PubId In (
SELECT Publisher.PubId
FROM Publisher
WHERE `PubName` = CONVERT( _utf8 'Methuen' USING latin1 ) COLLATE latin1_swedish_ci
)
)
)
);
I am basically trying to find out if a borrower has borrowed a book from the publisher Methuen. I just cant seem to work out what is wrong, I have gone through each individual statement and they all seem to work just not the overall request with all of the IN statements.
Can anyone spot what is wrong?
Like suggested, JOINs are a much cleaner, and likely a more efficient way to do this query as opposed to nested INs:
SELECT DISTINCT b.BorName
FROM
Borrower b
JOIN Loan l ON l.BorId = b.BorId
JOIN BookCopy bc ON bc.BcId = l.BcId
JOIN BookTitle bt ON bt.BtId = bc.BtId
JOIN Publisher p ON p.PubId = bt.PubID
WHERE
p.PubName = CONVERT( _utf8 'Methuen' USING latin1 ) COLLATE latin1_swedish_ci
Additionally, I think there was a problem in your first sub-query:
SELECT Borrower.BorId
FROM Loan
WHERE Loan.BcId IN...
I believe should have been:
SELECT Loan.BorId
FROM Loan
WHERE Loan.BcId IN...
Replace all the IN by =
Obviously using joins will be much cleaner.
I am not sure if MySQL supports the with clause but in SQL Server you are able to use something called a Common Table Expression. This is a ANSII SQL spec that should be easily determined.
Psuedo:
With
someMadeUpTableAlias AS
(
SELECT...
)
SELECT ...
FROM
OutsideTable AS A
someMadeUpTableAlias AS B ON (A. = B.)
I have been making a large effort to take advantage of the CTE's because of the readability inherently not there with subqueries. You may want to take a look at the side effects as behind the scenes it would be creating a temporary table and mysql may have some performance hits associated. Easiest way to tell is clear your query cache and run it both ways.