这是通过 table2 中的键从 table1 中列出数据的正确方法吗? (SQL)
Is this the right way to list data from table1 via a key in table 2? (SQL)
我完全是数据库的初学者,SQL 有一段时间我一直在为这个问题撞墙。在发布此内容之前,我曾尝试寻找答案,但我所能找到的只是更复杂的问题,其答案并不真正适用于我。
如果有任何机会这已经回答并且我错过了,我很抱歉。
Task: list names and last-names of all the workers that work in marketing.
Table1(workers) Table2(departments)
ID last-name name department# department# department-name
1 ... ... 2 2 marketing
2 ... ... 5 5 ...
3 ... ... 8 8 ...
4 ... ... 6 6 ...
这是我写的:
SELECT name, last-name
FROM workers, departments
WHERE departments.department# = workers.department# AND departments.department-name = "marketing"
在这种情况下,这是编写我的查询的正确方法吗?还是在查询的第二行中 "departments" 是多余的,因为我试图只列出名字和姓氏,它们都在"workers" table 而不是 "departments"。
如果这是正确的方法,是否有更好、更简洁的方法来达到相同的结果?
感谢您的帮助。
编辑:我又读了一些书,我很好奇这是否也行得通:
SELECT name, last-name
FROM workers
WHERE department# IN
(SELECT department#
FROM departments
WHERE department-name LIKE "Marketing%");
感谢您的宝贵时间。
我建议:
SELECT name, last-name
FROM workers INNER JOIN departments
ON workers.department# = departments.department#
WHERE department-name = 'marketing'
我完全是数据库的初学者,SQL 有一段时间我一直在为这个问题撞墙。在发布此内容之前,我曾尝试寻找答案,但我所能找到的只是更复杂的问题,其答案并不真正适用于我。 如果有任何机会这已经回答并且我错过了,我很抱歉。
Task: list names and last-names of all the workers that work in marketing.
Table1(workers) Table2(departments)
ID last-name name department# department# department-name
1 ... ... 2 2 marketing
2 ... ... 5 5 ...
3 ... ... 8 8 ...
4 ... ... 6 6 ...
这是我写的:
SELECT name, last-name
FROM workers, departments
WHERE departments.department# = workers.department# AND departments.department-name = "marketing"
在这种情况下,这是编写我的查询的正确方法吗?还是在查询的第二行中 "departments" 是多余的,因为我试图只列出名字和姓氏,它们都在"workers" table 而不是 "departments"。
如果这是正确的方法,是否有更好、更简洁的方法来达到相同的结果?
感谢您的帮助。
编辑:我又读了一些书,我很好奇这是否也行得通:
SELECT name, last-name
FROM workers
WHERE department# IN
(SELECT department#
FROM departments
WHERE department-name LIKE "Marketing%");
感谢您的宝贵时间。
我建议:
SELECT name, last-name
FROM workers INNER JOIN departments
ON workers.department# = departments.department#
WHERE department-name = 'marketing'