Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Bảng lừa đảo lệnh SQL - Cách học SQL trong 10 phút

Tôi là một nhà nghiên cứu AI, vì vậy một trong những việc chính mà tôi xử lý là dữ liệu. A của nó.

Với hơn 2,5 exabyte dữ liệu được tạo mỗi ngày , không có gì ngạc nhiên khi dữ liệu này cần được lưu trữ ở một nơi nào đó mà chúng ta có thể truy cập khi cần.

Bài viết này sẽ hướng dẫn bạn qua một bảng gian lận có thể hack được để giúp bạn thiết lập và chạy SQL một cách nhanh chóng.

SQL là gì?

SQL là viết tắt của Structured Query Language (Ngôn ngữ truy vấn có cấu trúc). Nó là một ngôn ngữ cho các hệ quản trị cơ sở dữ liệu quan hệ. SQL được sử dụng ngày nay để lưu trữ, truy xuất và thao tác dữ liệu trong cơ sở dữ liệu quan hệ.

Đây là cơ sở dữ liệu quan hệ cơ bản trông như thế nào:

Sử dụng SQL, chúng ta có thể tương tác với cơ sở dữ liệu bằng cách viết truy vấn.

Dưới đây là giao diện của một truy vấn mẫu:

SELECT * FROM customers;

Sử dụng SELECT này câu lệnh, truy vấn chọn tất cả dữ liệu từ tất cả các cột trong bảng của khách hàng và trả về dữ liệu như sau:

Ký tự đại diện dấu hoa thị (*) đề cập đến “ tất cả ”Và chọn tất cả các hàng và cột. Thay vào đó, chúng tôi có thể thay thế nó bằng các tên cột cụ thể - ở đây chỉ những cột đó mới được truy vấn trả về

SELECT FirstName, LastName FROM customers;

Thêm WHERE mệnh đề cho phép bạn lọc những gì được trả lại:

SELECT * FROM customers WHERE age >= 30 ORDER BY age ASC;

Truy vấn này trả về tất cả dữ liệu từ bảng sản phẩm với tuổi giá trị lớn hơn 30.

Việc sử dụng ORDER BY từ khóa chỉ có nghĩa là các kết quả sẽ được sắp xếp theo thứ tự bằng cách sử dụng cột tuổi từ giá trị thấp nhất đến cao nhất

Sử dụng INSERT INTO , chúng ta có thể thêm dữ liệu mới vào bảng. Dưới đây là một ví dụ cơ bản về việc thêm người dùng mới vào bảng khách hàng:

INSERT INTO customers(FirstName, LastName, address, email)
VALUES ('Jason', 'Dsouza', 'McLaren Vale, South Australia', '[email protected]');

Tất nhiên, những ví dụ này chỉ chứng minh một phần rất nhỏ những gì ngôn ngữ SQL có thể làm. Chúng tôi sẽ tìm hiểu thêm về nó trong hướng dẫn này.

Tại sao Học SQL?

Chúng ta đang sống trong thời đại của Dữ liệu lớn, nơi dữ liệu được sử dụng rộng rãi để tìm hiểu thông tin chi tiết và cung cấp thông tin về chiến lược, tiếp thị, quảng cáo và rất nhiều hoạt động khác.

Các doanh nghiệp lớn như Google, Amazon, AirBnb sử dụng cơ sở dữ liệu lớn, quan hệ làm cơ sở để cải thiện trải nghiệm của khách hàng. Hiểu SQL là một kỹ năng tuyệt vời không chỉ đối với các nhà khoa học và phân tích dữ liệu mà còn cho tất cả mọi người.

Làm thế nào để bạn nghĩ rằng bạn đột nhiên nhận được một quảng cáo Youtube về giày khi chỉ vài phút trước, bạn đang tìm kiếm đôi giày yêu thích của mình trên Google? Đó là SQL (hoặc một dạng SQL) đang hoạt động!

SQL so với MySQL

Trước khi chúng ta tiếp tục, tôi chỉ muốn làm rõ một chủ đề thường bị nhầm lẫn - sự khác biệt giữa SQL và MySQL. Hóa ra, họ không điều tương tự!

SQL là một ngôn ngữ, trong khi MySQL là một hệ thống để triển khai SQL.

SQL phác thảo cú pháp cho phép bạn viết các truy vấn quản lý cơ sở dữ liệu quan hệ.

MySQL là một cơ sở dữ liệu hệ thống chạy trên máy chủ. Nó cho phép bạn viết các truy vấn bằng cú pháp SQL để quản lý cơ sở dữ liệu MySQL.

Ngoài MySQL, có những hệ thống khác triển khai SQL. Một số cái phổ biến hơn bao gồm:

  • SQLite
  • Cơ sở dữ liệu Oracle
  • PostgreSQL
  • Máy chủ Microsoft SQL

Cách cài đặt MySQL

Đối với hầu hết các trường hợp, MySQL là lựa chọn ưu tiên cho hệ quản trị cơ sở dữ liệu. Nhiều Hệ thống quản lý nội dung phổ biến (như Wordpress) sử dụng MySQL theo mặc định, vì vậy sử dụng MySQL để quản lý các ứng dụng đó có thể là một ý tưởng hay.

Để sử dụng MySQL, bạn cần cài đặt MySQL trên hệ thống của mình:

Cài đặt MySQL trên Windows

Cách được khuyến nghị để cài đặt MySQL trên Windows là sử dụng trình cài đặt MSI từ trang web MySQL.

Tài nguyên này sẽ hướng dẫn bạn quá trình cài đặt.

Cài đặt MySQL trên macOS

Trên macOS, cài đặt MySQL cũng liên quan đến việc tải xuống trình cài đặt.

Tài nguyên này sẽ hướng dẫn bạn quá trình cài đặt.

Cách sử dụng MySQL

Với MySQL hiện đã được cài đặt trên hệ thống của bạn, tôi khuyên bạn nên sử dụng một số loại ứng dụng quản lý SQL để làm cho việc quản lý cơ sở dữ liệu của bạn trở thành một quá trình dễ dàng hơn nhiều.

Có rất nhiều ứng dụng để lựa chọn, phần lớn thực hiện cùng một công việc, vì vậy tùy thuộc vào sở thích cá nhân của bạn về việc sử dụng ứng dụng nào:

  • MySQL Workbench do Oracle phát triển
  • phpMyAdmin (hoạt động trong trình duyệt web)
  • HeidiSQL (Được đề xuất cho Windows)
  • Sequel Pro (Được đề xuất cho macOS)

Khi bạn đã sẵn sàng để bắt đầu viết các truy vấn SQL của riêng mình, hãy cân nhắc việc nhập dữ liệu giả thay vì tạo cơ sở dữ liệu của riêng bạn.

Dưới đây là một số cơ sở dữ liệu giả có sẵn để tải xuống miễn phí.

SQL Cheatsheet - The Icing on the Cake

Từ khóa SQL

Tại đây, bạn có thể tìm thấy một bộ sưu tập các từ khóa được sử dụng trong câu lệnh SQL, một mô tả và một ví dụ thích hợp. Một số từ khóa nâng cao hơn có phần dành riêng của chúng.

Trường hợp MySQL được đề cập bên cạnh một ví dụ, điều này có nghĩa là ví dụ này chỉ áp dụng cho cơ sở dữ liệu MySQL (trái ngược với bất kỳ hệ thống cơ sở dữ liệu nào khác).

ADD -- Adds a new column to an existing table

ADD CONSTRAINT -- Creates a new constraint on an existing table, which is used to specify rules for any data in the table.

ALTER TABLE -- Adds, deletes or edits columns in a table. It can also be used to add and delete constraints in a table, as per the above.

ALTER COLUMN -- Changes the data type of a table’s column.

ALL -- Returns true if all of the subquery values meet the passed condition.

AND -- Used to join separate conditions within a WHERE clause.

ANY -- Returns true if any of the subquery values meet the given condition.

AS -- Renames a table or column with an alias value which only exists for the duration of the query.

ASC -- Used with ORDER BY to return the data in ascending order.

BETWEEN -- Selects values within the given range.

CASE -- Changes query output depending on conditions.

CHECK -- Adds a constraint that limits the value which can be added to a column.

CREATE DATABASE -- Creates a new database.

CREATE TABLE -- Creates a new table. 

DEFAULT -- Sets a default value for a column

DELETE -- Delete data from a table.

DESC -- Used with ORDER BY to return the data in descending order.

DROP COLUMN -- Deletes a column from a table.

DROP DATABASE -- Deletes the entire database.

DROP DEAFULT -- Removes a default value for a column.

DROP TABLE -- Deletes a table from a database.

EXISTS -- Checks for the existence of any record within the subquery, returning true if one or more records are returned.

FROM -- Specifies which table to select or delete data from.

IN --  Used alongside a WHERE clause as a shorthand for multiple OR conditions.

INSERT INTO -- Adds new rows to a table.

IS NULL -- Tests for empty (NULL) values.

IS NOT NULL -- The reverse of NULL. Tests for values that aren’t empty / NULL.

LIKE -- Returns true if the operand value matches a pattern.

NOT -- Returns true if a record DOESN’T meet the condition.
 
OR -- Used alongside WHERE to include data when either condition is true.

ORDER BY -- Used to sort the result data in ascending (default) or descending order through the use of ASC or DESC keywords.

ROWNUM -- Returns results where the row number meets the passed condition.

SELECT -- Used to select data from a database, which is then returned in a results set.

SELECT DISTINCT -- Sames as SELECT, except duplicate values are excluded.

SELECT INTO -- Copies data from one table and inserts it into another.

SELECT TOP -- Allows you to return a set number of records to return from a table.

SET -- Used alongside UPDATE to update existing data in a table.

SOME -- Identical to ANY.

TOP -- Used alongside SELECT to return a set number of records from a table.

TRUNCATE TABLE -- Similar to DROP, but instead of deleting the table and its data, this deletes only the data.

UNION -- Combines the results from 2 or more SELECT statements and returns only distinct values.

UNION ALL -- The same as UNION, but includes duplicate values.

UNIQUE -- This constraint ensures all values in a column are unique.

UPDATE -- Updates existing data in a table.

VALUES -- Used alongside the INSERT INTO keyword to add new values to a table.

WHERE -- Filters results to only include data which meets the given condition.

Nhận xét trong SQL

Nhận xét cho phép bạn giải thích các phần trong câu lệnh SQL của mình mà không cần được thực thi trực tiếp.

Trong SQL, có 2 loại chú thích, một dòng và nhiều dòng.

Nhận xét dòng đơn trong SQL

Nhận xét dòng đơn bắt đầu bằng ‘- -’. Mọi văn bản sau 2 ký tự này đến cuối dòng sẽ bị bỏ qua.

-- This part is ignored

SELECT * FROM customers;

Nhận xét nhiều dòng trong SQL

Nhận xét nhiều dòng bắt đầu bằng / * và kết thúc bằng * /. Chúng trải dài trên nhiều dòng cho đến khi tìm thấy các ký tự đóng.

/*

This is a multiline comment.
It can span across multiple lines.

*/

SELECT * FROM customers;

/*

This is another comment. 
You can even put code within a comment to prevent its execution

SELECT * FROM icecreams;

*/

Các kiểu dữ liệu trong MySQL

Khi tạo bảng mới hoặc chỉnh sửa bảng hiện có, bạn phải chỉ định loại dữ liệu mà mỗi cột chấp nhận.

Trong ví dụ này, dữ liệu được chuyển đến id cột phải là một int (số nguyên), trong khi FirstName cột có VARCHAR kiểu dữ liệu có tối đa 255 ký tự.

CREATE TABLE customers(
id int,
FirstName varchar(255)
);

1. Các kiểu dữ liệu chuỗi

CHAR(size) -- Fixed length string which can contain letters, numbers and special characters. The size parameter sets the maximum string length, from 0 – 255 with a default of 1.

VARCHAR(size) -- Variable length string similar to CHAR(), but with a maximum string length range from 0 to 65535.

BINARY(size) -- Similar to CHAR() but stores binary byte strings.

VARBINARY(size) -- Similar to VARCHAR() but for binary byte strings.

TINYBLOB -- Holds Binary Large Objects (BLOBs) with a max length of 255 bytes.

TINYTEXT -- Holds a string with a maximum length of 255 characters. Use VARCHAR() instead, as it’s fetched much faster.

TEXT(size) -- Holds a string with a maximum length of 65535 bytes. Again, better to use VARCHAR().

BLOB(size) -- Holds Binary Large Objects (BLOBs) with a max length of 65535 bytes.

MEDIUMTEXT -- Holds a string with a maximum length of 16,777,215 characters.

MEDIUMBLOB -- Holds Binary Large Objects (BLOBs) with a max length of 16,777,215 bytes.

LONGTEXT -- Holds a string with a maximum length of 4,294,967,295 characters.

LONGBLOB -- Holds Binary Large Objects (BLOBs) with a max length of 4,294,967,295 bytes.

ENUM(a, b, c, etc…) -- A string object that only has one value, which is chosen from a list of values which you define, up to a maximum of 65535 values. If a value is added which isn’t on this list, it’s replaced with a blank value instead.

SET(a, b, c, etc…) -- A string object that can have 0 or more values, which is chosen from a list of values which you define, up to a maximum of 64 values.

2. Các kiểu dữ liệu số

BIT(size) -- A bit-value type with a default of 1. The allowed number of bits in a value is set via the size parameter, which can hold values from 1 to 64.

TINYINT(size) -- A very small integer with a signed range of -128 to 127, and an unsigned range of 0 to 255. Here, the size parameter specifies the maximum allowed display width, which is 255.

BOOL -- Essentially a quick way of setting the column to TINYINT with a size of 1. 0 is considered false, whilst 1 is considered true.

BOOLEAN	-- Same as BOOL.

SMALLINT(size) -- A small integer with a signed range of -32768 to 32767, and an unsigned range from 0 to 65535. Here, the size parameter specifies the maximum allowed display width, which is 255.

MEDIUMINT(size) -- A medium integer with a signed range of -8388608 to 8388607, and an unsigned range from 0 to 16777215. Here, the size parameter specifies the maximum allowed display width, which is 255.

INT(size) -- A medium integer with a signed range of -2147483648 to 2147483647, and an unsigned range from 0 to 4294967295. Here, the size parameter specifies the maximum allowed display width, which is 255.

INTEGER(size) -- Same as INT.

BIGINT(size) -- A medium integer with a signed range of -9223372036854775808 to 9223372036854775807, and an unsigned range from 0 to 18446744073709551615. Here, the size parameter specifies the maximum allowed display width, which is 255.

FLOAT(p) -- A floating point number value. If the precision (p) parameter is between 0 to 24, then the data type is set to FLOAT(), whilst if it's from 25 to 53, the data type is set to DOUBLE(). This behaviour is to make the storage of values more efficient.

DOUBLE(size, d) -- A floating point number value where the total digits are set by the size parameter, and the number of digits after the decimal point is set by the d parameter.

DECIMAL(size, d) -- An exact fixed point number where the total number of digits is set by the size parameters, and the total number of digits after the decimal point is set by the d parameter.

DEC(size, d) -- Same as DECIMAL.

3. Loại dữ liệu ngày / giờ

DATE -- A simple date in YYYY-MM–DD format, with a supported range from ‘1000-01-01’ to ‘9999-12-31’.

DATETIME(fsp) -- A date time in YYYY-MM-DD hh:mm:ss format, with a supported range from ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’. By adding DEFAULT and ON UPDATE to the column definition, it automatically sets to the current date/time.

TIMESTAMP(fsp) -- A Unix Timestamp, which is a value relative to the number of seconds since the Unix epoch (‘1970-01-01 00:00:00’ UTC). This has a supported range from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC.
By adding DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT TIMESTAMP to the column definition, it automatically sets to current date/time.

TIME(fsp) -- A time in hh:mm:ss format, with a supported range from ‘-838:59:59’ to ‘838:59:59’.

YEAR -- A year, with a supported range of ‘1901’ to ‘2155’.

Toán tử SQL

1. Toán tử số học trong SQL

+ -- Add
– -- Subtract
* -- Multiply
/ -- Divide
% -- Modulus

2. Toán tử Bitwise trong SQL

& -- Bitwise AND
| -- Bitwise OR
^-- Bitwise XOR

3. Toán tử so sánh trong SQL

= -- Equal to
> -- Greater than
< -- Less than
>= -- Greater than or equal to
<= -- Less than or equal to
<> -- Not equal to

4. Toán tử ghép trong SQL

+= -- Add equals
-= -- Subtract equals
*= -- Multiply equals
/= -- Divide equals
%= -- Modulo equals
&= -- Bitwise AND equals
^-= -- Bitwise exclusive equals
|*= -- Bitwise OR equals

Hàm SQL

1. Hàm chuỗi trong SQL

ASCII -- Returns the equivalent ASCII value for a specific character.

CHAR_LENGTH -- Returns the character length of a string.

CHARACTER_LENGTH -- Same as CHAR_LENGTH.

CONCAT -- Adds expressions together, with a minimum of 2.

CONCAT_WS -- Adds expressions together, but with a separator between each value.

FIELD -- Returns an index value relative to the position of a value within a list of values.

FIND IN SET -- Returns the position of a string in a list of strings.

FORMAT -- When passed a number, returns that number formatted to include commas (eg 3,400,000).

INSERT -- Allows you to insert one string into another at a certain point, for a certain number of characters.

INSTR -- Returns the position of the first time one string appears within another.

LCASE -- Converts a string to lowercase.

LEFT -- Starting from the left, extracts the given number of characters from a string and returns them as another.

LENGTH -- Returns the length of a string, but in bytes.

LOCATE -- Returns the first occurrence of one string within another,

LOWER -- Same as LCASE.

LPAD -- Left pads one string with another, to a specific length.

LTRIM -- Removes any leading spaces from the given string.

MID -- Extracts one string from another, starting from any position.

POSITION -- Returns the position of the first time one substring appears within another.

REPEAT -- Allows you to repeat a string

REPLACE -- Allows you to replace any instances of a substring within a string, with a new substring.

REVERSE	-- Reverses the string.

RIGHT -- Starting from the right, extracts the given number of characters from a string and returns them as another.

RPAD -- Right pads one string with another, to a specific length.

RTRIM -- Removes any trailing spaces from the given string.

SPACE -- Returns a string full of spaces equal to the amount you pass it.

STRCMP -- Compares 2 strings for differences

SUBSTR -- Extracts one substring from another, starting from any position.

SUBSTRING -- Same as SUBSTR

SUBSTRING_INDEX	-- Returns a substring from a string before the passed substring is found the number of times equals to the passed number.

TRIM --	Removes trailing and leading spaces from the given string. Same as if you were to run LTRIM and RTRIM together.

UCASE -- Converts a string to uppercase.

UPPER -- Same as UCASE.

2. Hàm số trong SQL

ABS -- Returns the absolute value of the given number.

ACOS -- Returns the arc cosine of the given number.

ASIN -- Returns the arc sine of the given number.

ATAN -- Returns the arc tangent of one or 2 given numbers.

ATAN2 -- Returns the arc tangent of 2 given numbers.

AVG -- Returns the average value of the given expression.

CEIL -- Returns the closest whole number (integer) upwards from a given decimal point number.

CEILING -- Same as CEIL.

COS -- Returns the cosine of a given number.

COT -- Returns the cotangent of a given number.

COUNT -- Returns the amount of records that are returned by a SELECT query.

DEGREES -- Converts a radians value to degrees.

DIV -- Allows you to divide integers.

EXP -- Returns e to the power of the given number.

FLOOR -- Returns the closest whole number (integer) downwards from a given decimal point number.

GREATEST -- Returns the highest value in a list of arguments.

LEAST -- Returns the smallest value in a list of arguments.

LN -- Returns the natural logarithm of the given number.

LOG -- Returns the natural logarithm of the given number, or the logarithm of the given number to the given base.

LOG10 -- Does the same as LOG, but to base 10.

LOG2 -- Does the same as LOG, but to base 2.

MAX -- Returns the highest value from a set of values.

MIN -- Returns the lowest value from a set of values.

MOD -- Returns the remainder of the given number divided by the other given number.

PI -- Returns PI.

POW -- Returns the value of the given number raised to the power of the other given number.

POWER -- Same as POW.

RADIANS -- Converts a degrees value to radians.

RAND -- Returns a random number.

ROUND -- Rounds the given number to the given amount of decimal places.

SIGN -- Returns the sign of the given number.

SIN -- Returns the sine of the given number.

SQRT -- Returns the square root of the given number.

SUM -- Returns the value of the given set of values combined.

TAN -- Returns the tangent of the given number.

TRUNCATE -- Returns a number truncated to the given number of decimal places.

3. Hàm ngày trong SQL

ADDDATE -- Adds a date interval (eg: 10 DAY) to a date (eg: 20/01/20) and returns the result (eg: 20/01/30).

ADDTIME -- Adds a time interval (eg: 02:00) to a time or datetime (05:00) and returns the result (07:00).

CURDATE -- Gets the current date.

CURRENT_DATE -- Same as CURDATE.

CURRENT_TIME -- Gest the current time.

CURRENT_TIMESTAMP -- Gets the current date and time.

CURTIME -- Same as CURRENT_TIME.

DATE -- Extracts the date from a datetime expression.

DATEDIFF -- Returns the number of days between the 2 given dates.

DATE_ADD -- Same as ADDDATE.

DATE_FORMAT -- Formats the date to the given pattern.

DATE_SUB -- Subtracts a date interval (eg: 10 DAY) to a date (eg: 20/01/20) and returns the result (eg: 20/01/10).

DAY -- Returns the day for the given date.

DAYNAME -- Returns the weekday name for the given date.

DAYOFWEEK -- Returns the index for the weekday for the given date.

DAYOFYEAR -- Returns the day of the year for the given date.

EXTRACT -- Extracts from the date the given part (eg MONTH for 20/01/20 = 01).

FROM DAYS -- Returns the date from the given numeric date value.

HOUR -- Returns the hour from the given date.

LAST DAY -- Gets the last day of the month for the given date.

LOCALTIME -- Gets the current local date and time.

LOCALTIMESTAMP -- Same as LOCALTIME.

MAKEDATE -- Creates a date and returns it, based on the given year and number of days values.

MAKETIME -- Creates a time and returns it, based on the given hour, minute and second values.

MICROSECOND -- Returns the microsecond of a given time or datetime.

MINUTE -- Returns the minute of the given time or datetime.

MONTH -- Returns the month of the given date.

MONTHNAME -- Returns the name of the month of the given date.

NOW -- Same as LOCALTIME.

PERIOD_ADD -- Adds the given number of months to the given period.

PERIOD_DIFF -- Returns the difference between 2 given periods.

QUARTER -- Returns the year quarter for the given date.

SECOND -- Returns the second of a given time or datetime.

SEC_TO_TIME -- Returns a time based on the given seconds.

STR_TO_DATE -- Creates a date and returns it based on the given string and format.

SUBDATE -- Same as DATE_SUB.

SUBTIME -- Subtracts a time interval (eg: 02:00) to a time or datetime (05:00) and returns the result (03:00).

SYSDATE -- Same as LOCALTIME.

TIME -- Returns the time from a given time or datetime.

TIME_FORMAT -- Returns the given time in the given format.

TIME_TO_SEC -- Converts and returns a time into seconds.

TIMEDIFF -- Returns the difference between 2 given time/datetime expressions.

TIMESTAMP -- Returns the datetime value of the given date or datetime.

TO_DAYS -- Returns the total number of days that have passed from ‘00-00-0000’ to the given date.

WEEK -- Returns the week number for the given date.

WEEKDAY -- Returns the weekday number for the given date.

WEEKOFYEAR -- Returns the week number for the given date.

YEAR -- Returns the year from the given date.

YEARWEEK -- Returns the year and week number for the given date.

4. Các hàm khác trong SQL

BIN -- Returns the given number in binary.

BINARY -- Returns the given value as a binary string.

CAST -- Converst one type into another.

COALESCE -- From a list of values, returns the first non-null value.

CONNECTION_ID -- For the current connection, returns the unique connection ID.

CONV -- Converts the given number from one numeric base system into another.

CONVERT -- Converts the given value into the given datatype or character set.

CURRENT_USER -- Returns the user and hostname which was used to authenticate with the server.

DATABASE -- Gets the name of the current database.

GROUP BY -- Used alongside aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the results.

HAVING -- Used in the place of WHERE with aggregate functions.

IF -- If the condition is true it returns a value, otherwise it returns another value.

IFNULL -- If the given expression equates to null, it returns the given value.

ISNULL -- If the expression is null, it returns 1, otherwise returns 0.

LAST_INSERT_ID -- For the last row which was added or updated in a table, returns the auto increment ID.

NULLIF -- Compares the 2 given expressions. If they are equal, NULL is returned, otherwise the first expression is returned.

SESSION_USER -- Returns the current user and hostnames.

SYSTEM_USER -- Same as SESSION_USER.

USER -- Same as SESSION_USER.

VERSION -- Returns the current version of the MySQL powering the database.

Ký tự đại diện trong SQL

Trong SQL, Ký tự đại diện là các ký tự đặc biệt được sử dụng với LIKENOT LIKE từ khóa. Điều này cho phép chúng tôi tìm kiếm dữ liệu có các mẫu phức tạp khá hiệu quả.

% -- Equates to zero or more characters.
-- Example: Find all customers with surnames ending in ‘ory’.
SELECT * FROM customers
WHERE surname LIKE '%ory';

_ -- Equates to any single character.
-- Example: Find all customers living in cities beginning with any 3 characters, followed by ‘vale’.
SELECT * FROM customers
WHERE city LIKE '_ _ _vale';

[charlist] -- Equates to any single character in the list.
-- Example: Find all customers with first names beginning with J, K or T.
SELECT * FROM customers
WHERE first_name LIKE '[jkt]%';

Khóa SQL

Trong cơ sở dữ liệu quan hệ, có một khái niệm về sơ cấp nước ngoài chìa khóa. Trong bảng SQL, chúng được bao gồm dưới dạng ràng buộc, trong đó bảng có thể có khóa chính, khóa ngoại hoặc cả hai.

1. Khóa chính trong SQL

Một bản ghi chính cho phép mỗi bản ghi trong một bảng được xác định duy nhất. Bạn chỉ có thể có một khóa chính cho mỗi bảng và bạn có thể gán ràng buộc này cho bất kỳ đơn hoặc tổ hợp cột nào. Tuy nhiên, điều này có nghĩa là mỗi giá trị trong (các) cột này cần phải là duy nhất.

Thông thường trong một bảng, cột ID là khóa chính và thường được ghép nối với AUTO_INCREMENT từ khóa. Điều này có nghĩa là giá trị tự động tăng khi và khi các bản ghi mới được tạo.

Ví dụ (MySQL)

Tạo một bảng mới và đặt khóa chính cho cột ID.

Khách hàng
CREATE TABLE customers (
id int NOT NULL AUTO_INCREMENT,
FirstName varchar(255),
Last Name varchar(255) NOT NULL,
address varchar(255),
email varchar(255),
PRIMARY KEY (id)
);

2. Khóa ngoại trong SQL

Bạn có thể áp dụng khóa ngoại cho một hoặc nhiều cột. Bạn sử dụng nó để liên kết 2 bảng cùng nhau trong cơ sở dữ liệu quan hệ.

Bảng chứa khóa ngoại được gọi là con chìa khóa,

Bảng chứa khóa (hoặc ứng cử viên) được tham chiếu được gọi là cha bảng.

Về cơ bản, điều này có nghĩa là dữ liệu cột được chia sẻ giữa 2 bảng, vì khóa ngoại cũng ngăn việc chèn dữ liệu không hợp lệ, dữ liệu không có trong bảng mẹ.

Ví dụ (MySQL)

Tạo một bảng mới và biến bất kỳ cột nào tham chiếu đến ID trong các bảng khác thành khóa ngoại.

CREATE TABLE orders (
id int NOT NULL,
user_id int,
product_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);

Chỉ mục trong SQL

Chỉ mục là các thuộc tính có thể được gán cho các cột thường xuyên được tìm kiếm để làm cho quá trình truy xuất dữ liệu nhanh hơn và hiệu quả hơn.

CREATE INDEX -- Creates an index named ‘idx_test’ on the first_name and surname columns of the users table. In this instance, duplicate values are allowed.
CREATE INDEX idx_test
ON users (first_name, surname);
CREATE UNIQUE INDEX -- The same as the above, but no duplicate values.
CREATE UNIQUE INDEX idx_test
ON users (first_name, surname);
DROP INDEX -- Removes an index.
ALTER TABLE users
DROP INDEX idx_test;

Tham gia SQL

Trong SQL, một JOIN mệnh đề được sử dụng để trả về một kết quả kết hợp dữ liệu từ nhiều bảng, dựa trên một cột chung có trong cả hai bảng.

Có một số liên kết khác nhau có sẵn để bạn sử dụng:

  • Tham gia bên trong (Mặc định): Trả về bất kỳ bản ghi nào có giá trị phù hợp trong cả hai bảng.
  • Tham gia bên trái: Trả về tất cả các bản ghi từ bảng đầu tiên, cùng với mọi bản ghi phù hợp từ bảng thứ hai.
  • Tham gia phù hợp: Trả về tất cả các bản ghi từ bảng thứ hai, cùng với mọi bản ghi phù hợp từ bảng đầu tiên.
  • Tham gia đầy đủ: Trả về tất cả các bản ghi từ cả hai bảng khi có sự trùng khớp.

Một cách phổ biến để hình dung cách thức hoạt động của các phép nối là như thế này:

SELECT orders.id, users.FirstName, users.Surname, products.name as ‘product name’
FROM orders
INNER JOIN users on orders.user_id = users.id
INNER JOIN products on orders.product_id = products.id;

Chế độ xem trong SQL

Một dạng xem về cơ bản là một tập kết quả SQL được lưu trữ trong cơ sở dữ liệu dưới một nhãn, vì vậy bạn có thể quay lại nó sau mà không cần phải chạy lại truy vấn.

Những điều này đặc biệt hữu ích khi bạn có một truy vấn SQL tốn kém mà bạn có thể cần một số lần. Vì vậy, thay vì chạy đi chạy lại để tạo ra cùng một tập hợp kết quả, bạn chỉ có thể thực hiện một lần và lưu dưới dạng xem.

Cách tạo chế độ xem trong SQL

Để tạo một dạng xem, bạn có thể làm như sau:

CREATE VIEW priority_users AS
SELECT * FROM users
WHERE country = ‘United Kingdom’;

Sau đó, trong tương lai, nếu bạn cần truy cập vào tập kết quả đã lưu trữ, bạn có thể thực hiện như sau:

SELECT * FROM [priority_users];

Cách thay thế các chế độ xem trong SQL

Với CREATE OR REPLACE , bạn có thể cập nhật dạng xem như sau:

CREATE OR REPLACE VIEW [priority_users] AS
SELECT * FROM users
WHERE country = ‘United Kingdom’ OR country=’USA’;

Cách xóa chế độ xem trong SQL

Để xóa một chế độ xem, chỉ cần sử dụng DROP VIEW lệnh.

DROP VIEW priority_users;

Kết luận

Phần lớn các trang web và ứng dụng sử dụng cơ sở dữ liệu quan hệ theo cách này hay cách khác. Điều này làm cho SQL trở nên cực kỳ có giá trị vì nó cho phép bạn tạo các hệ thống chức năng, phức tạp hơn.

Hãy chắc chắn theo dõi tôi trên Twitter để cập nhật các bài viết trong tương lai. Chúc bạn học vui vẻ!



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. mysql error 1364 Trường không có giá trị mặc định

  2. Những gì cần giám sát trong MySQL 8.0

  3. Làm cách nào để sử dụng tính năng băm mật khẩu với PDO để làm cho mã của tôi an toàn hơn?

  4. Cách kết nối Cơ sở dữ liệu MySQL với Trang web PHP

  5. Chọn một máy chủ tìm kiếm toàn văn bản độc lập:Sphinx hay SOLR?