mysql从多个表中选择唯一值

时间:2015-07-28 15:20:33

标签: mysql relational-database

我的数据如下:

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语句以仅提取主题/子主题组合所独有的任务?

1 个答案:

答案 0 :(得分:0)

You need to join all three tables (topic doesn't appear in the FROM clause of your query but does in the WHERE clause).

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