仍在学习MySQL绳索,我正试图找出如何进行涉及多对多的特定选择。如果表名太通用我很抱歉,我只是做了一些自制的练习。我尽我所能成为一名自学者。
我有3个表,其中一个是链接表。如何撰写声明“显示哪些用户同时拥有HTC和三星手机”(他们拥有2部手机)。我猜测答案是在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 |
+------+-------+
答案 0 :(得分:13)
密钥在GROUP BY / HAVING中使用COUNT个DISTINCT电话名称。当计数为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;
答案 1 :(得分:0)
我认为您正在寻找的答案是:
"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'"
我相信,如果您从mark5中提取不同的名称,并在电话名称为HTC或三星的特定值上加入其他表格,我会回答您的问题