cs

 

7. Workers

[Problem]

The following data definition defines an organization's employee hierarchy.

An employee is a manager if any other employee has their managerId set to this employee's id. That means John is a manager if at least one other employee has their managerId set to John's id.

Write a query that selects only the names of employees who are not managers.

 

[My Answer]

1
2
3
4
5
6
7
8
9
10
11
#first_try
select name 
from employees
where managerId is null;
 
 
#Answer
select name 
from employees
where id not in
(select managerId from employees where managerId is not null);
cs

 


8. Users And Roles

[Problem]

The following two tables are used to define users and their respective roles:

The users_roles table should contain the mapping between each user and their roles. Each user can have many roles, and each role can have many users.

Modify the provided SQLite create table statement so that:

  • Only users from the users table can exist within users_roles.
  • Only roles from the roles table can exist within users_roles.
  • A user can only have a specific role once.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#first_try
CREATE TABLE users_roles (
  userId INTEGER NOT NULL,
  roleId INTEGER NOT NULL,
  FOREIGN KEY (userId) REFERENCES users (id),
  FOREIGN KEY (roleId) REFERENCES roles (id));
 
 
#Answer
CREATE TABLE users_roles (
  userId INTEGER NOT NULL,
  roleId INTEGER NOT NULL,
  FOREIGN KEY (userId) REFERENCES users (id),
  FOREIGN KEY (roleId) REFERENCES roles (id),
  UNIQUE (userId, roleId));
cs

 It was really hard for me, and also I couldn't solve the last problem (Regional Sales Comparison) yet... If I have a chance to learn SQL queries from a good tutor, I will pay coffee in every class for my tutor... 
 

 

'Code Problems > SQL_Testdome' 카테고리의 다른 글

SQL Interview Questions_part 2  (0) 2021.05.15
SQL Interview Questions_part 1  (0) 2021.05.15

+ Recent posts