mysql select 来自多个表的唯一值
mysql select unique values from multiple tables
我有这样的数据:
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
我很难抓住任务而不在任务中重复它们 table。
我目前的陈述是这样的:
INSERT INTO TASKS
SELECT
master.task,
subtopics.id
FROM master,subtopics
WHERE master.subtopic = subtopic.name
AND master.topic = topic.name
当我 运行 它时,结果给了我 2 个 'use poles' 实例,一个指向子主题 1,另一个指向子主题 3 - 这是不正确的。
我如何 运行 SELECT 语句只提取 topic/subtopic 组合独有的任务?
您需要连接所有三个表(主题未出现在查询的 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
我有这样的数据:
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
我很难抓住任务而不在任务中重复它们 table。
我目前的陈述是这样的:
INSERT INTO TASKS
SELECT
master.task,
subtopics.id
FROM master,subtopics
WHERE master.subtopic = subtopic.name
AND master.topic = topic.name
当我 运行 它时,结果给了我 2 个 'use poles' 实例,一个指向子主题 1,另一个指向子主题 3 - 这是不正确的。
我如何 运行 SELECT 语句只提取 topic/subtopic 组合独有的任务?
您需要连接所有三个表(主题未出现在查询的 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