简体   繁体   English

MySQL多对多选择

[英]MySQL Many-To-Many Select

Still learning the MySQL ropes and I'm trying to find out how to do a specific selection involving many-to-many. 仍在学习MySQL绳索,我正试图找出如何进行涉及多对多的特定选择。 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. 我有3个表,其中一个是链接表。 How do I write the statement which says "Show which users own both an HTC and a Samsung phone" (they own 2 phones). 如何编写“显示哪些用户同时拥有HTC和三星手机” (他们拥有2部手机)的声明。 I'm guessing the answer is in the WHERE statement but I can't figure out how to word it. 我猜测答案是在WHERE语句中,但我无法弄清楚如何说出来。

-- 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 |
+------+-------+

The key is in the GROUP BY/HAVING using a COUNT of DISTINCT phone names. 关键是在GROUP BY / HAVING中使用COUNT个DISTINCT电话名称。 When the count is 2, you'll know the user has both phones. 当计数为2时,您将知道用户同时拥有两部手机。

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;

The answer I think you are looking for is: 我认为您正在寻找的答案是:

"SELECT DISTINCT mark5.name FROM mark5 JOIN mark4 ON (mark4.uid = mark5.uid) JOIN mark3 ON (mark3.phoneid = mark4.phoneid) WHERE mark3.name = 'HTC' && mark3.name = 'Samsung'"

I believe that will answer your questions where you are pulling the Distinct Names from mark5 and joining your other tables on those specific values where phone name is HTC or Samsung 我相信,如果您从mark5中提取不同的名称,并在电话名称为HTC或Samsung的特定值上加入您的其他表格,我会回答您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM