一尘不染

MySql 自 JOIN 查询

sql

我有这张表

mysql> describe skill_usage;
+----------+---------+------+-----+---------+-------+
| Field    | Type    | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| skill_id | int(11) | NO   | MUL | NULL    |       |
| job_id   | int(11) | NO   | MUL | NULL    |       |
+----------+---------+------+-----+---------+-------+

并且知道在我的数据中,有一个job_id(6) 用于skill_id3 和 4:

mysql>  select * from skill_usage;
+----------+--------+
| skill_id | job_id |
+----------+--------+
|        1 |      1 |
|        2 |      2 |
|        3 |      3 |     <----  matches only one part of the AND clause
|        3 |      4 |     <----  matches only one part of the AND clause
|        2 |      5 |
|        3 |      6 |     <==== matches both parts of the AND clause
|        4 |      6 |     <====
|        2 |      7 |
+----------+--------+
8 rows in set (0.00 sec)

这是我尝试过的:

SELECT DISTINCT s1.job_id FROM skill_usage AS s1 
  INNER JOIN skill_usage AS s2 ON s1.job_id = s2.job_id
    WHERE s1.skill_id IN (3,4)
    AND   s2.skill_id IN (3,4)

我认为这意味着“找到所有job_idskill_id3 和skill_id4匹配的”。

显然不是:

mysql> SELECT DISTINCT s1.job_id FROM skill_usage AS s1
    ->   INNER JOIN skill_usage AS s2 ON s1.job_id = s2.job_id
    ->     WHERE s1.skill_id IN (3,4)
    ->     AND   s2.skill_id IN (3,4);
+--------+
| job_id |
+--------+
|      3 |
|      4 |
|      6 |
+--------+
3 rows in set (0.00 sec)

我做错了什么?我的查询应该如何阅读?我认为是时候写一本好书或 Udemy 课程了,但我没有自己的封面自我加入。

我的查询正确地找到job_id= 6,但错误地(IMO)找到了job_id3 和 4。我希望他们无法通过该AND条款。


阅读 459

收藏
2021-07-01

共1个答案

一尘不染

您可以在此处使用聚合:

SELECT job_id
FROM skill_usage
WHERE skill_id IN (3, 4)
GROUP BY job_id
HAVING MIN(skill_id) <> MAX(skill_id);

此查询应受益于以下索引:

CREATE INDEX idx ON skill_usage (skill_id, job_id);

所写的WHEREandHAVING子句都是sargable,并且应该能够利用这个索引。

2021-07-01