搜尋
首頁資料庫mysql教程MySQL学习足迹记录12--使用子查询_MySQL

bitsCN.com

MySQL学习足迹记录12--使用子查询

 

1.子查询(subquery):即嵌套在其他查询中的查询

原始数据如下:

 

   mysql> SELECT order_num FROM orderitems;+-----------+| order_num |+-----------+|     20005 ||     20005 ||     20009 ||     20005 ||     20009 ||     20008 ||     20006 ||     20009 ||     20009 ||     20005 ||     20007 |+-----------+11 rows in set (0.01 sec)mysql> SELECT cust_id FROM orders;+---------+| cust_id |+---------+|   10001 ||   10001 ||   10003 ||   10004 ||   10005 |+---------+5 rows in set (0.01 sec)现在先分步查询step1:  mysql> SELECT order_num          -> FROM orderitems          -> WHERE prod_id = 'TNT2';+-----------+| order_num |+-----------+|     20005 ||     20007 |+-----------+2 rows in set (0.00 sec)step2: mysql> SELECT cust_id FROM orders          -> WHERE order_num IN( 20005,20007);+---------+| cust_id |+---------+|   10001 ||   10004 |+---------+2 rows in set (0.00 sec) Step3:  使用子查询把step1,step2组合起来(即把20005,20007换掉)  mysql> SELECT cust_id           -> FROM orders           -> WHERE order_num IN( SELECT order_num           ->                                        FROM orderitems           ->                                         WHERE prod_id = 'TNT2');+---------+| cust_id |+---------+|   10001 ||   10004 |+---------+2 rows in set (0.00 sec)TIPS:  在SELECT语句中,子查询总是从内向外处理的。  子查询可以嵌套多重 step4:  mysql> SELECT cust_name,cust_contact           -> FROM customers           -> WHERE cust_id IN (10001,10004);      #(10001,10004)既是step3查询的结果+----------------+--------------+| cust_name      | cust_contact |+----------------+--------------+| Coyote Inc.    | Y Lee        || Yosemite Place | Y Sam        |+----------------+--------------+2 rows in set (0.01 sec)step5:把step4的IN (10001,10004)换成子查询 mysql> SELECT cust_name,cust_contact          -> FROM customers         -> WHERE cust_id IN (SELECT cust_id         ->                                   FROM orders         ->                                   WHERE order_num IN (SELECT order_num         ->                                                                           FROM orderitems         ->                                                                           WHERE prod_id = 'TNT2'));+----------------+--------------+| cust_name      | cust_contact |+----------------+--------------+| Coyote Inc.    | Y Lee        || Yosemite Place | Y Sam        |+----------------+--------------+2 rows in set (0.00 sec)

 

 

2.计算字段使用子查询

   原始数据

   mysql> SELECT cust_id FROM orders;+---------+| cust_id |+---------+|   10001 ||   10001 ||   10003 ||   10004 ||   10005 |+---------+5 rows in set (0.01 sec)mysql> SELECT cust_id FROM customers;+---------+| cust_id |+---------+|   10001 ||   10002 ||   10003 ||   10004 ||   10005 |+---------+5 rows in set (0.00 sec)mysql> SELECT cust_id,(SELECT COUNT(*) FROM orders         ->                                WHERE orders.cust_id = customers.cust_id) AS orders        -> FROM customers       -> ORDER BY cust_id;+---------+--------+              | cust_id | orders |+---------+--------+|   10001 |      2 ||   10002 |      0 ||   10003 |      1 ||   10004 |      1 ||   10005 |      1 |+---------+--------+5 rows in set (0.00 sec)

 

 

TIPS:

  子查询最常见的使用是在WHERE子句的IN操作符中,以及用来填充计算列

bitsCN.com
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何在MySQL中刪除或修改現有視圖?如何在MySQL中刪除或修改現有視圖?May 16, 2025 am 12:11 AM

todropaviewInmySQL,使用“ dropviewifexistsview_name;” andTomodifyAview,使用“ createOrreplaceViewViewViewview_nameAsSelect ...”。 whendroppingaview,asew dectivectenciesanduse和showcreateateviewViewview_name;“ tounderStanditSsstructure.whenModifying

MySQL視圖:我可以使用哪些設計模式?MySQL視圖:我可以使用哪些設計模式?May 16, 2025 am 12:10 AM

mySqlViewScaneFectectialized unizedesignpatternslikeadapter,Decorator,Factory,andObserver.1)adapterPatternadaptSdataForomDifferentTablesIntoAunifiendView.2)decoratorPatternenhancateDataWithCalcalcualdCalcalculenfields.3)fieldfields.3)

在MySQL中使用視圖的優點是什麼?在MySQL中使用視圖的優點是什麼?May 16, 2025 am 12:09 AM

查看InMysqlareBeneForsImplifyingComplexqueries,增強安全性,確保dataConsistency,andOptimizingPerformance.1)他們simimplifycomplexqueriesbleiesbyEncapsbyEnculatingThemintoreusableviews.2)viewsEnenenhancesecuritybyControllityByControllingDataAcces.3)

如何在MySQL中創建一個簡單的視圖?如何在MySQL中創建一個簡單的視圖?May 16, 2025 am 12:08 AM

toCreateAsimpleViewInmySQL,USEthecReateaTeviewStatement.1)defitEtheetEtheTeViewWithCreatEaTeviewView_nameas.2)指定usethectstatementTorivedesireddata.3)usethectStatementTorivedesireddata.3)usetheviewlikeatlikeatlikeatlikeatlikeatlikeatable.views.viewssimplplifefifydataaccessandenenanceberity but consisterfort,butconserfort,consoncontorfinft

MySQL創建用戶語句:示例和常見錯誤MySQL創建用戶語句:示例和常見錯誤May 16, 2025 am 12:04 AM

1)foralocaluser:createUser'localuser'@'@'localhost'Indidendify'securepassword'; 2)foraremoteuser:creationuser's creationuser'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Rocaluser'@'localhost'Indidendify'seceledify'Securepassword'; 2)

在MySQL中使用視圖的局限性是什麼?在MySQL中使用視圖的局限性是什麼?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他們不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinsOrsubqueries.2)他們canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

確保您的MySQL數據庫:添加用戶並授予特權確保您的MySQL數據庫:添加用戶並授予特權May 14, 2025 am 12:09 AM

porthusermanagementinmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素會影響我可以在MySQL中使用的觸發器數量?哪些因素會影響我可以在MySQL中使用的觸發器數量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)複雜的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!