.Do not display duplicate records in query results
Do not display duplicate records when querying mainly applies the DISTINCT keyword, which is used to delete duplicate records.
When implementing query operations, if the query's select list contains the primary key of a table, then the records in each query will be unique (because the primary key has a different value in each record); if the primary key does not Included in the query results, duplicate records may appear. Use the DISTINCT keyword to delete duplicate records. The syntax of
DISTINCT is as follows:
SELECT DISTINCT select_list;
Note: The DISTINCT keyword does not refer to a certain row, but refers to all columns output by SELECT without duplication. This is important because it prevents the same rows from appearing in the output of a query.
For example:
select distinct name,price,date,address,quality from tb;
2. Use NOT to query records that do not meet the conditions
Use the condition formed by combining NOT with the predicate to query. The expressions formed by combining
NOT with predicates are [NOT] BETWEEN, IS [NOT] NULL and [NOT] IN respectively.
(1)[NOT] BETWEEN
This condition specifies the inclusive range of values, using AND to separate the start value and the end value.
The syntax is as follows:
test_expression [NOT] BETWEEN begin_expression AND end_expression
The result type is boolean and the return value is: If the value of test_expression is less than or equal to the value of begin_expression or greater than or equal to the value of end_expression, then NOT BETWEEN returns true.
Note: To specify an exclusion range, you can also use the greater than (>) and less than (<) operators instead of BETWEEN. <)運算符代替 BETWEEN。
(2)IS [NOT] NULL
Queries for null or non-null values ??according to the keyword specified. If any operand is null, the expression evaluates to null.
(3) [NOT] IN
Specifies the expression to be queried based on whether the keyword used is included in the list or excluded from the list. Query expressions can use permutations or column names, and lists can be a set of permutations or subqueries (more often). If the list is a set of constants, it should be placed within a pair of parentheses.
The syntax is as follows:
test_expression [NOT] in( subquery expression[,...n] )
Parameter description:
①test_expression: SQL expression
②subquery: A subquery containing a certain column result set, which must have the same data type as test_expression.
③expression[,...n]: A list of expressions used to test whether they match. All expressions must be of the same data type as test_expression j.
For example:
select * from tb where selldate not between '2016-10-30' and '2016-12-12';
3. Use the subquery as an expression
Apply the subquery in the SELECT clause, and the query structure can appear in the form of an expression. There are some control rules when applying subqueries. Understanding these rules will help you better master the application of subqueries.
①The inner query SELECT list or IN introduced by the comparison operator contains only one expression or column name. Columns named in the WHERE clause of the outer statement must be join-compatible with columns named in the query's SELECT list.
②Subqueries introduced by immutable comparison operators (comparison operators not followed by the keywords ANY and ALL) cannot include a GROUP BY clause or a HAVING clause unless the group or individual values ??are predetermined.
③The SELECT list introduced by EXISTS generally consists of asterisks (*), without specifying specific column names, and you can also nest subqueries to limit rows in the WHERE clause.
④Subqueries cannot process their results internally, that is, subqueries cannot include an ORDER BY clause. The optional DISTINCT keyword is useful for sorting subquery results, since some systems eliminate duplicate records by sorting the results first.
For example: display the total scores of all students and the difference between the students’ total scores and the school’s average score.
select stuId , stuName, (Math+Language+English) Total , round((select avg(Math+Language+English) from tb),0) Averages, round(((Math+Language+English)-(select avg(Math+Language+English) from tb)),0) Average from tb;
4. Use subqueries as derived tables
In practical applications, subqueries are often used as derived tables, that is, the result set of the query is used as a table.
Subquery is an additional method for handling multi-table operations. The syntax structure is as follows:
(SELECT [ALL|DISTINCT]<select item list> From <table list> [WHERE <search condition>] [GROUP BY<group item list> [HAVING <group by search condition>]] )
For example:
Group the sales orders according to the product name statistics and query the products with sales quantity greater than 14 (use the group statistics as a derived table)
select * from (select proname ,COUNT(*) as sl from td GROUP BY proname) WHERE (sl > 14) ;
Perform the top 100 sales quantity in the product sales table Group statistics (use filtered data as a derived table)
select sl,count(*) from ( select * from tb ORDER BY zdbh LIMIT 0,100) GROUP BY sl;
Statistics of the amount owed by unsettled customers in the customer relationship table (use filtered data as a derived table)
select name,sum(xsje) from (select * from tb where NOT pay) GROUP BY name;
Query all warrior training information and query the third shooting score greater than 8 Ring warrior information (use the results of one query as the table operated by another query)
select T.soldId, T.soldName, T.FrirstGun, T.SecondGun, T.ArtideGun from (select * from tb where ArtideGun>8) as T;
Note: The derived table must be aliased.
5. Relate data through subqueries
Use EXISTS predicate to introduce subqueries. In some cases, as long as the subquery returns a true or false value, only whether the predicate condition is met is considered, and the data content itself is not important. At this point you can use the EXISTS predicate to define a subquery. The EXISTS predicate is true if the subquery returns one or more rows, false otherwise. For the EXISTS predicate to work, the query conditions should be established in the subquery to match the values ??in the two tables joined by the subquery.
The syntax is as follows:
EXISTS subquery
Parameter description:
subquery:一個受限的 SQL 語句(不允許有 COMPUTE 子句和 INTO 關鍵字) 。
例如:獲取英語成績大于90分的學生信息
select name,college,address from tb_Stu where exists (select name from tb_grades M where M.name=I.name and English>90) ;
備注:EXISTS 謂詞子查詢中的 SELECT 子句中可使用任何列名,也可以使用任何多個列。這種謂詞值只注重是否返回行,而不注重行的內(nèi)容,用戶可以指定列名或者只使用一個“*”。
6.實現(xiàn)笛卡爾乘積查詢
笛卡爾乘積查詢實現(xiàn)了兩張表之間的交叉連接,在查詢語句中沒有 WHERE 查詢條件,返回到結(jié)果集中的數(shù)據(jù)行數(shù)等于第一個表中符合查詢條件的數(shù)據(jù)行數(shù)乘以第二個表中符合條件的數(shù)據(jù)行數(shù)。
笛卡爾乘積的關鍵字是 CROSS JOIN 。例如,用戶信息表中有2條數(shù)據(jù),職工信息表中有4條數(shù)據(jù),當這兩張表應用笛卡爾乘積進行查詢時,查詢的結(jié)果就是2×4=8條。
例如:
select EmpId,EmpName,Depatment,JobTitle,Wages from tb_employees a cross join tb_position b;
備注:在進行多表查詢時需要主注意,由于多表可能會出現(xiàn)相同的字段,因此在指定查詢字段時,最好為重復的字段起別名,以方便區(qū)分。
7.使用 UNION 并運算
UINON 指的是并運算,即從兩個或多個類似的結(jié)果集中選擇行,并將其組合在一起形成一個單獨的結(jié)果集。
UINON 運算符主要用于將兩個或更多查詢結(jié)果組合為單個結(jié)果集,該結(jié)果集包含聯(lián)合查詢中所有查詢的全部行。在使用 UNION 運算符時應遵循以下準則:
①在使用 UNION 運算符組合的語句中,所有選擇列表的表達式數(shù)目必須相同(列名、算術表達式、聚集函數(shù)等)。
②在使用 UNION 運算符組合的結(jié)果集中的相應列或個別查詢中使用的任意列的子集必須具有相同的數(shù)據(jù)類型,并且兩者數(shù)據(jù)類型之間必須存在可能的隱性轉(zhuǎn)換或提供了顯式轉(zhuǎn)換。
③利用 UNION 運算符組合的各語句中對應的結(jié)果集列出現(xiàn)的順序必須相同,因為 UNION 運算符是按照各個查詢給定的順序逐個比較各列。
④ UNION 運算符組合不同的數(shù)據(jù)類型時,這些數(shù)據(jù)類型將使用數(shù)據(jù)類型優(yōu)先級的規(guī)則進行轉(zhuǎn)換。
⑤通過 UNION 運算符生產(chǎn)的表中列名來自 UNION 語句中的第一個單獨的查詢。若要用新名稱引用結(jié)果集中的某列,必須按第一個 SELECT 語句中的方式引用該列。
例如:
select filenumuber,name,juior,address from tb union select filenumuber,name,senior,address from tk;
8.內(nèi)外連接查詢
1)內(nèi)聯(lián)接(典型的聯(lián)接運算,使用像 = 或 <> 之類的比較運算符)。包括相等聯(lián)接和自然聯(lián)接。
內(nèi)聯(lián)接使用比較運算符根據(jù)每個表共有的列的值匹配兩個表中的行。例如,檢索 students和courses表中學生標識號相同的所有行。
內(nèi)連接可以分為等值連接、自然連接和不等值連接。
等值連接使用等號運算符比較被連接列的值,在查詢結(jié)果中將列出連接表中的所有列,包括重復列。等值連接返回所有連接表中具有匹配值的行。
等值連接查詢的語法如下:
select fildList from table1 inner join table2 on table1.column = table2.column;
參數(shù)說明:
fildList:要查詢的字段列表。
2)外聯(lián)接。外聯(lián)接可以是左向外聯(lián)接、右向外聯(lián)接或完整外部聯(lián)接。
在 FROM子句中指定外聯(lián)接時,可以由下列幾組關鍵字中的一組指定:
1)LEFT JOIN或LEFT OUTER JOIN
左向外聯(lián)接的結(jié)果集包括 LEFT OUTER子句中指定的左表的所有行,而不僅僅是聯(lián)接列所匹配的行。如果左表的某行在右表中沒有匹配行,則在相關聯(lián)的結(jié)果集行中右表的所有選擇列表列均為空值。
2)RIGHT JOIN 或 RIGHT OUTER JOIN
右向外聯(lián)接是左向外聯(lián)接的反向聯(lián)接。將返回右表的所有行。如果右表的某行在左表中沒有匹配行,則將為左表返回空值。例如 ,表 A 右外連接表 B,結(jié)果為公共部分 C 加表 B 的結(jié)果集。如果表 A 中沒有與表 B 匹配的項,就是用 NULL 進行連接。
3)FULL JOIN 或 FULL OUTER JOIN
完整外部聯(lián)接返回左表和右表中的所有行。當某行在另一個表中沒有匹配行時,則另一個表的選擇列表列包含空值。如果表之間有匹配行,則整個結(jié)果集行包含基表的數(shù)據(jù)值。
3)交叉聯(lián)接
交叉聯(lián)接返回左表中的所有行,左表中的每一行與右表中的所有行組合。交叉聯(lián)接也稱作笛卡爾積。
FROM 子句中的表或視圖可通過內(nèi)聯(lián)接或完整外部聯(lián)接按任意順序指定;但是,用左或右向外聯(lián)接指定表或視圖時,表或視圖的順序很重要。有關使用左或右向外聯(lián)接排列表的更多信息,請參見使用外聯(lián)接。
例子:
-------------------------------------------------
a表 id name b表 id job parent_id 1 張3 1 23 1 2 李四 2 34 2 3 王武 3 34 4 a.id同parent_id 存在關系
--------------------------------------------------
1) 內(nèi)連接
select a.*,b.* from a inner join b on a.id=b.parent_id 結(jié)果是 : 1 張3 1 23 1 2 李四 2 34 2
-------------------------------------------------
2)左連接
select a.*,b.* from a left join b on a.id=b.parent_id 結(jié)果是 1 張3 1 23 1 2 李四 2 34 2 3 王武 null
-------------------------------------------------
3) 右連接
select a.*,b.* from a right join b on a.id=b.parent_id 結(jié)果是 1 張3 1 23 1 2 李四 2 34 2 null 3 34 4
-------------------------------------------------
4) 完全連接
select a.*,b.* from a full join b on a.id=b.parent_id 結(jié)果是 張3 1 23 1 李四 2 34 2 null 3 34 4 王武 nul
-------------------------------------------------
備注:內(nèi)連接與外連接區(qū)別?
內(nèi)連接只返回兩張表相匹配的數(shù)據(jù);而外連接是對內(nèi)連接的擴展,可以使查詢更具完整性,不會丟失數(shù)據(jù)。下面舉例說明兩者區(qū)別。
假設有兩張表,分別為表A 與 表B,兩張表公共部分為 C 。
內(nèi)連接的連接結(jié)果是兩個表都存在記錄,可以說 A 內(nèi)連 B 得到的是 C。
表 A 左外連接B,那么A不受影響,查詢結(jié)果為公共部分C 加表A的記錄集。
表A右外連接B,那么B不受影響,查詢結(jié)果為公共部分C加表B的記錄集。
全外連接表示兩張表都不加限制。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

Why do I need SSL/TLS encryption MySQL connection? Because unencrypted connections may cause sensitive data to be intercepted, enabling SSL/TLS can prevent man-in-the-middle attacks and meet compliance requirements; 2. How to configure SSL/TLS for MySQL? You need to generate a certificate and a private key, modify the configuration file to specify the ssl-ca, ssl-cert and ssl-key paths and restart the service; 3. How to force SSL when the client connects? Implemented by specifying REQUIRESSL or REQUIREX509 when creating a user; 4. Details that are easily overlooked in SSL configuration include certificate path permissions, certificate expiration issues, and client configuration requirements.

To achieve MySQL deployment automation, the key is to use Terraform to define resources, Ansible management configuration, Git for version control, and strengthen security and permission management. 1. Use Terraform to define MySQL instances, such as the version, type, access control and other resource attributes of AWSRDS; 2. Use AnsiblePlaybook to realize detailed configurations such as database user creation, permission settings, etc.; 3. All configuration files are included in Git management, support change tracking and collaborative development; 4. Avoid hard-coded sensitive information, use Vault or AnsibleVault to manage passwords, and set access control and minimum permission principles.

To collect user behavior data, you need to record browsing, search, purchase and other information into the database through PHP, and clean and analyze it to explore interest preferences; 2. The selection of recommendation algorithms should be determined based on data characteristics: based on content, collaborative filtering, rules or mixed recommendations; 3. Collaborative filtering can be implemented in PHP to calculate user cosine similarity, select K nearest neighbors, weighted prediction scores and recommend high-scoring products; 4. Performance evaluation uses accuracy, recall, F1 value and CTR, conversion rate and verify the effect through A/B tests; 5. Cold start problems can be alleviated through product attributes, user registration information, popular recommendations and expert evaluations; 6. Performance optimization methods include cached recommendation results, asynchronous processing, distributed computing and SQL query optimization, thereby improving recommendation efficiency and user experience.

PHP plays the role of connector and brain center in intelligent customer service, responsible for connecting front-end input, database storage and external AI services; 2. When implementing it, it is necessary to build a multi-layer architecture: the front-end receives user messages, the PHP back-end preprocesses and routes requests, first matches the local knowledge base, and misses, call external AI services such as OpenAI or Dialogflow to obtain intelligent reply; 3. Session management is written to MySQL and other databases by PHP to ensure context continuity; 4. Integrated AI services need to use Guzzle to send HTTP requests, safely store APIKeys, and do a good job of error handling and response analysis; 5. Database design must include sessions, messages, knowledge bases, and user tables, reasonably build indexes, ensure security and performance, and support robot memory

When choosing a suitable PHP framework, you need to consider comprehensively according to project needs: Laravel is suitable for rapid development and provides EloquentORM and Blade template engines, which are convenient for database operation and dynamic form rendering; Symfony is more flexible and suitable for complex systems; CodeIgniter is lightweight and suitable for simple applications with high performance requirements. 2. To ensure the accuracy of AI models, we need to start with high-quality data training, reasonable selection of evaluation indicators (such as accuracy, recall, F1 value), regular performance evaluation and model tuning, and ensure code quality through unit testing and integration testing, while continuously monitoring the input data to prevent data drift. 3. Many measures are required to protect user privacy: encrypt and store sensitive data (such as AES

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction
