Suppose that in table "ab" I have the names of the students that get along from class "a" and class "b", identically I have table "ac" and "bc". What SQL query should I use in order to get all the combinations possible of students who can form groups (i.e. "get along together")? And how can i extend this to n classes?
For example: John from class a gets along with Jen from class b and Steff from class c, and Jen and Steff get along. Therefore John, Jen and Steff can form a group).
For this I would create two tables, a student table (id, name, class) and a relationship table (student1, student2). You might also want to add a class table for the time, location etc of the class.
A friendship would have two relationships (2,3) and (3,2) to describe it as two way. One way might be a follower or fan of another student.
This will scale up to a lot more than 3 classes.
Then you can use multiple joins to get friends of friends and so on to an arbitrary depth.
Here is a query to get friends of friends (fof):
SELECT fof_details.*
FROM relationships r
INNER JOIN relationships fof
ON r.student2 = fof.student1
INNER JOIN student fof_details
ON fof_details.id = fof.student2
WHERE r.student1 = '12';
There are also database engines made specifically for doing graph modeling like this.
http://openquery.com/blog/graph-engine-mkii
This query should return all students who can be in one group with John.
WITH ABC AS (SELECT AB.A, AB.B, AC.C FROM (SELECT * FROM AB
INNER JOIN BC
ON AB.B=BC.B)
INNER JOIN AC
ON (AC.C=BC.C AND AB.A=AC.A))
SELECT STUDENT FROM (
SELECT AB.B STUDENT FROM ABC WHERE AB.A='John'
UNION
SELECT AC.C STUDENT FROM ABC WHERE AB.A='John')
GROUP BY STUDENT
PS.: Written fast without any syntax check, hope you'll be able to bring this to work :)
The initial query can be satisfied by the code
select ab.a, ab.b, ac.c
from
ab inner join
bc on ab.b = bc.b inner join
ac on ac.a = ab.a and bc.c = ac.c
Stepping up to n classes will get progressively more complex as n=4 would be the same query with the additional three joins
inner join ad on ab.a = ad.a
inner join bd on bd.b = ab.b and ad.d = bd.d
inner join cd on cd.c = ac.c and ad.d = cd.d
2 classes requires 1 table and no joins,
3 classes requires 3 tables and 2 joins,
4 classes requires 6 tables and 5 joins
So we can see it getting progressively more complex as we proceed
First you don't want to have a table for each class. You are capturing the same type of information in multiple tables and this is generally considered a bad practice. You want to "normalize" your data so that the same data exists in one place.
Second, name your tables appropriately so that you understand what you are actually trying to build. Maybe you are generalizing to mask what your intentions for the actual implementations are by using "ab" in the question, but if you are doing this in your actual code it will hurt you in the long run.
It appears you need a people table with names and a friends table where you track who is friends with who:
create table people ( id int, name char(128) );
create table friends ( id int, person_id int, friend_id int );
Then you just need to have the query to get the groups:
SELECT person.* FROM friends
INNER JOIN friends grp
ON friends.friend_id = grp.person_id
INNER JOIN people person
ON person.id = grp.friend_id
WHERE friends.person_id = 42;
Related
Members is a table of persons who are members of a club. Various details of each member are included in this table through various columns such as ID, name, address, email, etc.
Now, any two members of this table can have a relationship. For example, if A, B, C, and D are all members of this table, then A and B can have a relation; A can C have a relation; B and D can have relations, etc. So, while member A can have a relation with all other members (such as B, C, and D, etc.), he can have a relation with any other member in, either way, i.e., it can be A-B or B-A.
For this relationship, a new table Relations has been created. This has only 3 columns; namely, ID, FirstMemberID, SecondMemberID. Here, both FirstMemberID and SecondMemberID are basically the respective IDs of members (in a relationship) from the Members table.
Now, I want to construct an SQL query (for MySQL) to select full details (all columns) from the Members table for all those members who have a relationship with a person with ID of XYZ in such a manner that XYZ is the first part of this relationship. Here XYZ is only the ID of the person and not his name.
So, I can this first query:
SELECT SecondMemberID FROM Relations WHERE FirstMemberID = XYZ;
This query gives multi-results because XYZ has relations with many members.
The other select statement is like this:
SELECT * FROM Members WHERE ID = SecondMemberID;
[Note: Here, SecondMemberID is what is returned from the first query. But, as I said, there can be many SecondMemberID here.]
My problem is how to combine the two queries in such a way that I get proper results.
I have tried various methods, like treating the results of the first query as an array and then using IN operator in the second query by using the implode method of PHP or otherwise. I have also tried various JOIN statements but without success.
What am I missing? Can you please help?
Try
SELECT Members.*
FROM Relations LEFT JOIN Members
ON (Relations.SecondMemberID=Members.ID)
WHERE Relations.FirstMemberID = XYZ;
You need a simple JOIN command in SQL. JOIN joins two tables. INNER JOIN joins them on a specific condition, i.e. concatenates two rows (one from each table) that match the condition. Condition is usually something like: table1.field1 == table2.field2 or you can use LEFT or RIGHT JOIN which will, in turn, join two rows but the right or left one can be empty.
I think you want:
SELECT SecondMemberID
FROM Relations
WHERE Id IN (SELECT SecondMemberID
FROM Members
WHERE FirstMemberID = 'XYZ');
I am developing a friend system, which handles friend requests and friendships.
I have a table named Member where I keep information about each member including their id, first and last name
and another table named Friendships where I keep track of the id of the first friend Friend1 and the second Friend2 and the date of the friendship formation.(Note: each request is recorded twice in my database; ex 1 -> 2 and 2->1 )
I am trying to write a query to display the first and last name of the friends of the current user. I know I have to INNER JOIN both tables, but I am not sure ON what exactly.
Assuming the friend table and members table have same ID columns,
SELECT m.first, m.second
FROM m.member INNER JOIN f.friendships
ON f.id = m.id;
Could be somthings like this
select a.firstname, b.lastname from Member a
inner join Friendships b on (b.friend1_id = a.id )
and a.id = 'current_user_id'
On the foreign keys (I guess Members.Id=Friendships.Friend1) but it really depends on the semantics you are implementing with those duplicate (bidirectional?) friendship relations.
I'm searching for an equivalent for MySQL "FIELD_IN_SET()" with joined tables. Here is an example of what I want to do.
I have three tables. The first contains fields "user_id" and "user_name". The second contains fields "id", "user_id" and "role_id". The third contains "id", "role_name".
I want to search for users that owns two different specified roles. After LEFT JOINs, my table will look like this :
user_id - user_name - role_name
12 - Yoda - jedi
12 - Yoda - master
15 - Obi-Wan Kenobi - jedi
The first question is : How to search for users that are both "jedi" and "master".
The second question is : Is it better (optimization || readability) to do it on PHP side (getting all results in an array and do some loop to verify what I want to do) or directly in the MySQL query, knowing that I will have to build the query dynamically (it's for a PHP/MySQL search engine in a great user database).
Thank you :) .
user1527491
This problem is called RELATION DIVISION
SELECT a.user_name
FROM firstTable a
INNER JOIN secondTable b
ON a.user_ID = b.user_ID
INNER JOIN thirstTable c
ON b.role_ID = c.role_ID
WHERE c.role_NAME IN ('jedi', 'master')
GROUP BY a.user_name
HAVING COUNT(*) = 2
SQL of Relational Division
If a unique constraint was not define for role_NAME for every user_name, DISTINCT keyword is needed.
SELECT a.user_name
FROM firstTable a
INNER JOIN secondTable b
ON a.user_ID = b.user_ID
INNER JOIN thirstTable c
ON b.role_ID = c.role_ID
WHERE c.role_NAME IN ('jedi', 'master')
GROUP BY a.user_name
HAVING COUNT(DISTINCT c.role_NAME) = 2
I'm having a small problem making a query in MySQL.
I have the following tables:
member;
group;
member_has_group (this one has the columns id_group referes to the group id and id_member referes to member id)
I'm trying to make a query that gives me the members from a selected group. Can you help me?
I'm not familiar with join tables, but for the search i made i think thats probably one of the solutions.
Thanks in advance.
Elkas
If you know the group id
select member.* from member m
inner join member_has_group mg on m.id = mg.id_member
where mg.id_group = [x]
If you only know the group name
select member.* from member m
inner join member_has_group mg on m.id = mg.id_member
inner join group g on g.id = mg.id_group
where g.name = 'group name'
This is trival in SQL :
SELECT m.id_member, m.name
FROM member AS m
INNER JOIN member_has_group AS h ON (m.id_member=h.id_member)
WHERE (h.id_group=#my_id_group)
#my_id_group is the group id you have to give.
Yep, you need a join here.
SELECT *
FROM `member`
JOIN `group` ON member.id = group.id
JOIN `member_has_group` ON group.id = member_has_group.id
Depending on the information in your tables, you may not need the third table at all.You only need a connector table with you have a "many to many" relationship between then.
(Ignore the rest if you already know
about database normalization)
For example, if you had two tables, Authors and Books. Authors would contain fields such as Name, Publisher, Birthday, whatever is a property of the "author". Books would contain relevant "book" information. This is a "one-to-many" relationship. An author may be linked (via a field such as author_id) to several books, but a book can only have one author. You would not need a third table here.
Building on that, say you had a third table for "Character Names". This would be a list of main character names used in any of the books in the "Books" table. One of the characters happens to be named John Steele. John has a whole series of books written about him. In the Books table, several of the books may list John Steele as a character. While in the characters table, John Steele could be listed in several books. This is "many-to-many". You need a third table here. It would only have two fields. A book_id and character_id, one entry for each book that John Steele appears in.
MySql Manual on DB Normalization
I am writing an application that helps book exchange between users.
I am using PHP and MySQL, and I am pretty new to them both.
I have 5 tables, 3 data tables and 2 service tables:
user: with user attributes (user_id, name, birth... etc).
book: with book attributes (book_id, name, author, publisher... etc).
copy: represents actual copies of a books (copy_id, condition, comments... etc).
user_copy: describes which user holds which copy, composed out of userID and copyID.
copy_book: represents the connection of copy and book, composed out of copyID and bookID
My question is:
what is the easiest and most efficient statement for getting the
book attributes and copy attributes for each copy that a user holds?
You need to inner join all the tables that you are interested in: book, copy, user_copy, and copy_book. The SELECT statement that returns attributes on all copies held by a user may look like this:
SELECT B.bookID
, B.name
, B.author
, B.publisher
, C.condition
, C.comments
-- you may get other fields that you are interested in here..
FROM book B
INNER JOIN copy_book CB ON B.bookID = CB.bookID
INNER JOIN user_copy UC ON UC.copyID = CB.copyID
INNER JOIN copy C ON C.copyID = UC.copyID
WHERE UC.userID = <the user Id that you want>
I hope it's pretty clear what the statement does but if you have any questions, please ask.