Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Many-To-Many Select

Tags:

mysql

Still learning the MySQL ropes and I'm trying to find out how to do a specific selection involving many-to-many. I apologize if the table names are too generic, I was just doing some self-made exercises. I try my best to be a self-learner.

I have 3 tables one of which is a linking table. How do I write the statement which says "Show which users own both an HTC and a Samsung phone" (they own 2 phones). I'm guessing the answer is in the WHERE statement but I can't figure out how to word it.

-- Table: mark3
+---------+-----------+
| phoneid | name      |
+---------+-----------+
|       1 | HTC       |
|       2 | Nokia     |
|       3 | Samsung   |
|       4 | Motorolla |
+---------+-----------+

-- Table: mark4
+------+---------+
| uid  | phoneid |
+------+---------+
|    1 |       1 |
|    1 |       2 |
|    2 |       1 |
|    2 |       3 |
|    2 |       4 |
|    3 |       1 |
|    3 |       3 |
+------+---------+

-- Table: mark5
+------+-------+
| uid  | name  |
+------+-------+
|    1 | John  |
|    2 | Paul  |
|    3 | Peter |
+------+-------+
like image 329
enchance Avatar asked Nov 09 '11 20:11

enchance


People also ask

How to represent many-to-many in SQL?

Many-to-many (M:M) A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa. To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

How should many-to-many relationship be handled?

When you have a many-to-many relationship between dimension-type tables, we provide the following guidance: Add each many-to-many related entity as a model table, ensuring it has a unique identifier (ID) column. Add a bridging table to store associated entities. Create one-to-many relationships between the three tables.

How do you fetch data from many many relationships in SQL?

Try this one: SELECT book_title, subject_name FROM Book INNER JOIN Book_Author ON Book. book_ISBN = Book_Author. book_ISBN INNER JOIN Author ON Book_Author.


1 Answers

The key is in the GROUP BY/HAVING using a COUNT of DISTINCT phone names. When the count is 2, you'll know the user has both phones.

SELECT m5.name
    FROM mark5 m5
        INNER JOIN mark4 m4
            ON m5.uid = m4.uid
        INNER JOIN mark3 m3
            ON m4.phoneid = m3.phoneid
    WHERE m3.name in ('HTC', 'Samsung')
    GROUP BY m5.name
    HAVING COUNT(DISTINCT m3.name) = 2;
like image 76
Joe Stefanelli Avatar answered Oct 13 '22 10:10

Joe Stefanelli