SQL online brushing questions

Niuke.com learning SQL online programming, Niuke.com online programming , a total of 82 courses

Website for practice, running SQL online

At present, there are 43, and I can’t brush it anymore. I will find a chance to do the rest later.

insert image description here

Only record questionable questions

Simple

SQL196 Check the third from the bottom

Find all information about the employee with the third-last-last entry time

SELECT emp_no, birth_date, first_name, last_name, gender, hire_date
FROM employees
WHERE hire_date = (
    SELECT DISTINCT hire_date
    FROM employees
    ORDER BY hire_date DESC
    LIMIT 2,1
);

puzzled

The codes of the first few rankings are all like this. This code does solve the problem that there are multiple records in the penultimate and penultimate. However, if there are multiple records in the penultimate third, LIMIT only takes one record, so only one is taken. man?

Through practice, it is found LIMITthat a record is taken, but a value in parentheses is given to hire_date. You can match multiple records

practice

CREATE TABLE Person (
	PersonID int,
	City int
);

INSERT INTO Person VALUES (1, 1);
INSERT INTO Person VALUES (2, 1);
INSERT INTO Person VALUES (3, 2);
INSERT INTO Person VALUES (4, 2);
INSERT INTO Person VALUES (5, 3);
INSERT INTO Person VALUES (6, 3);
INSERT INTO Person VALUES (7, 3);

SELECT *
FROM Person
WHERE City = (
    SELECT DISTINCT City
    FROM Person
    LIMIT 2,1
);

search result

5|3
6|3
7|3

SQL201 GROUP BY

Find the employee number emp_no with more than 15 salary records and the corresponding number of records t

SELECT emp_no, COUNT(*)
FROM salaries
GROUP BY emp_no
HAVING COUNT(*)>15;

Note

When using aggregate functions (SUM\COUNT...), sum must be used GROUP BY, HAVINGotherwise an error will be reported

SQL204 Check if...

Get all non-manager employees emp_no

SELECT emp_no
FROM employees
WHERE emp_no NOT IN (
    SELECT emp_no
    FROM dept_manager
);

Note

NOT IN+subquery

SQL211 check salary second

Get the emp_no of the employee with the second highest salary and its corresponding salary salary

SELECT emp_no, salary
FROM salaries
WHERE salary = (
    SELECT salary
    FROM salaries
    GROUP BY salary
    ORDER BY salary DESC
    LIMIT 1,1
)

understand

  1. Since there may be multiple employees with the same salary, useGROUP BY
  2. Find high salary, use reverse order
  3. emp_no defaults to ascending order

SQL228 batch insert

Batch insert data

INSERT INTO actor(actor_id, first_name, last_name, last_update)
VALUES ('1', 'PENELOPE', 'GUINESS', '2006-02-15 12:34:33'),
('2', 'NICK', 'WAHLBERG', '2006-02-15 12:34:33');

Note

  1. Column names without quotes, values ​​with quotes
  2. Insert multiple data ,separated by

SQL236 delete duplicates, keep the smallest id

Delete the duplicate records of emp_no, and only keep the record corresponding to the smallest id.

DELETE FROM titles_test
WHERE id NOT IN (
    SELECT * FROM (
        SELECT MIN(id)
        FROM titles_test
        GROUP BY emp_no
    )a
);

Note

  1. Keep the minimum, delete the NOT IN minimum
  2. You can't check and delete:
DELETE FROM titles_test
WHERE id NOT IN(
    SELECT MIN(id)
    FROM titles_test
    GROUP BY emp_no
);

​ Can only rename the resulting new table

SQL238 replace

Replace the row data of id=5 and emp_no=10001 with id=5 and emp_no=10005

UPDATE titles_test
SET emp_no=REPLACE(emp_no, 10001, 10005)
WHERE id=5;

SQL239 modify table name

Change the titles_test table name to titles_2017

alter table titles_test rename to titles_2017;

SQL258 outer join

find everyone's tasks

SELECT P.id, P.name, T.content
FROM person AS P LEFT OUTER JOIN task AS T
ON P.id=T.person_id;

SQL260 max

The latest login date of everyone in Niuke (1)

SELECT user_id, MAX(date)
FROM login
GROUP BY user_id
ORDER BY user_id;

Note

  1. The MAX function is directly written in the content to be queried
  2. ORDER BY still needs to be added, don’t be lazy

SQL266 retains three decimal places

Exam Score (1)

SELECT job, ROUND(AVG(score),3) as s
FROM grade
GROUP BY job
ORDER BY s DESC;

medium

SQL205 Get department manager

Get the current manager of all employees

SELECT E.emp_no, M.emp_no AS manager
FROM dept_emp AS E, dept_manager AS M
WHERE E.dept_no = M.dept_no
AND E.emp_no != M.emp_no;

SQL213 three-table outer join

Find the last_name and first_name of all employees and the corresponding dept_name

SELECT E.last_name, E.first_name, a.dept_name
FROM employees AS E LEFT OUTER JOIN (
    SELECT D.dept_no, D.dept_name, DE.emp_no //注意
    FROM departments AS D, dept_emp AS DE
    WHERE D.dept_no = DE.dept_no
)AS a
ON E.emp_no = a.emp_no;

Note

  1. Three-table outer join query, first the two-table join is named a, and then the outer join
  2. SELECT * cannot be used when connecting two tables, because both tables have dept_no attribute

SQL223 NULL

Use the join query method to find out the movie id and name without classification

SELECT F.film_id, F.title
FROM film AS F LEFT OUTER JOIN film_category AS FC
ON F.film_id = FC.film_id
WHERE FC.category_id is NULL;

Note

  1. To query records without a certain attribute, first perform an outer connection, and then filter by WHERE

SQL224 subquery

Use subquery to find the title and description of all movies belonging to the Action category

SELECT F.title, F.description
FROM film AS F LEFT OUTER JOIN film_category AS FC
ON F.film_id = FC.film_id
WHERE FC.film_id IN (
    SELECT FC.film_id
    FROM category AS C LEFT OUTER JOIN film_category AS FC
    ON C.category_id = FC.category_id
    WHERE C.name = 'Action'
);

Note

  1. Remember to add ON for connection
  2. If multiple statements are detected, use IN

SQL231 Create an index

Create a unique index uniq_idx_firstname on first_name

ALTER TABLE actor ADD UNIQUE uniq_idx_firstname(first_name);
ALTER TABLE actor ADD INDEX idx_lastname(last_name);

SQL232 Create view

Create view actor_name_view against actor table

CREATE VIEW actor_name_view (first_name_v, last_name_v) AS
SELECT first_name, last_name
FROM actor;

SQL233 mandatory index

Create an index idx_emp_no for the above salaries table emp_no field

SELECT *
FROM salaries
FORCE INDEX (idx_emp_no)
WHERE emp_no = 10005;

Replenish:

  1. Another syntax for adding an index:

    create index idx_emp_no on salaries(emp_no);
    
  2. Why use mandatory indexing

SQL234 add new column

Add a new column named create_date after last_update

ALTER TABLE actor ADD COLUMN
create_date datetime NOT NULL DEFAULT '2020-10-01 00:00:00';

SQL235 trigger

Construct a trigger audit_log

CREATE TRIGGER audit_log
AFTER INSERT ON employees_test
FOR EACH ROW
BEGIN
    INSERT INTO audit VALUES(new.ID, new.NAME);
END

understand

  1. This trigger is to insert the first two columns of data into the audit table when inserting data into employees_test
  2. AFTERIndicates the trigger time, INSERTindicating the trigger event

SQL240 foreign key

Create a foreign key constraint on the audit table, whose emp_no corresponds to the primary key of the employees_test table

ALTER TABLE audit
ADD CONSTRAINT FOREIGN KEY (emp_no)
REFERENCES employees_test(id);

SQL242 Salary increase by 10%

Increase current salaries of all bonus employees by 10%

UPDATE salaries AS s INNER JOIN emp_bonus as e
ON s.emp_no = e.emp_no
SET salary = salary * 1.1
WHERE to_date = '9999-01-01';

SQL244 concat

Connect the last_name and first_name of all employees in the employees table with quotation marks

SELECT CONCAT(RTRIM(last_name),"'",LTRIM(first_name)) AS name
FROM employees;

Number of commas in SQL245

Find the number of occurrences of a comma in a string

SELECT id, LENGTH(string)-LENGTH(REPLACE(string, ',', '')) AS cnt
FROM strings;

SQL246 take two letters

Get the first_name in employees

SELECT first_name
FROM employees
ORDER BY RIGHT(first_name, 2);

SQL247 grouping and merging strings

Aggregate by dept_no

SELECT dept_no, GROUP_CONCAT(emp_no) AS employees
FROM dept_emp
GROUP BY dept_no;

SQL248 removes part of the value and takes the average

average salary

SELECT (SUM(salary)-MAX(salary)-MIN(salary)) / (COUNT(1)-2) AS avg_salary
FROM salaries
WHERE to_date = '9999-01-01';

おすすめ

転載: blog.csdn.net/qq_50209297/article/details/130665856