我的数据如下所示:
table:master
topic| subtopic | task
recreation | skiiing | use poles
recreation | skiiing | wax skiis
events | block party | run electricity
events | skiing | purchase banner
我将数据移动到关系型 mysql 数据库中,所以它看起来像这样
table: topics
id | name
1 | recreation
2 | events
----------------------
table : subtopics
id | name | topic
1 | skiing | 1
2 | block party | 2
3 | skiing | 2
我很难在任务表中不重复的情况下抓取任务。
我当前的声明如下:
INSERT INTO TASKS
SELECT
master.task,
subtopics.id
FROM master,subtopics
WHERE master.subtopic = subtopic.name
AND master.topic = topic.name
当我运行它时,结果给了我 2 个“使用极点”实例,一个指向子主题 1,另一个指向子主题 3 - 这是不正确的。
如何运行 SELECT 语句以仅提取主题/子主题组合特有的任务?
最佳答案
您需要连接所有三个表(主题不会出现在查询的 FROM 子句中,但会出现在 WHERE 子句中)。
INSERT INTO TASKS
SELECT master.task, subtopics.id
FROM master
JOIN topic ON master.topic = topic.name
JOIN subtopics ON master.subtopic = subtopics.name AND subtopics.topic = topic.id
关于mysql从多个表中选择唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31680622/