在MySQL中使用子查詢和標量子查詢的基本用法

2021-09-07 15:00:28 字數 1549 閱讀 7304

一、mysql 子查詢

子查詢是將乙個 select 語句的查詢結果作為中間結果,供另乙個 sql 語句呼叫。mysql 支援 sql 標準要求的所有子查詢格式和操作,也擴充套件了特有的幾種特性。

子查詢沒有固定的語法,乙個子查詢的例子如下:

select * from article where uid in (select uid from user where status=1)//取status=1時的uid子集
對應的兩個資料表如下:

user 使用者表:

查詢返回結果如下所示:

在該例子中,首先通過子查詢語句查詢出所有 status=1 的 uid,實際的查詢類似於:

select * from article where uid in(1,2)
二、mysql 標量子查詢

標量子查詢是指子查詢返回的是單一值的標量,如乙個數字或乙個字串,也是子查詢中最簡單的返回形式。

乙個標量子查詢的例子如下:

select * from article where uid = (select uid from user where status=1 order by uid desc limit 1)
在該例子中,子查詢語句:select uid from user where status=1 order by uid desc limit 1

返回的是單一的數字(如 2),實際的查詢語句為:select * from article where uid = 2

1、使用子查詢進行比較:可以使用 = > < >= <= <> 這些操作符對子查詢的標量結果進行比較,通常子查詢的位置在比較式的右側:

select * from t1 where column1 = (select max(column2) from t2)
2、子查詢與表連線:子查詢與表連線很類似,可思考2種的互換寫法,有助於理解在很多情況下,子查詢的效果與 join 表連線很類似,但一些特殊情況下,是必須用子查詢而不能用表連線的,如:

MySQL在字段中使用select子查詢

前幾天看別人的 中看到在字段中使用select子查詢的方法,第一次見這種寫法,然後研究了一下,記錄下來 大概的形式是這樣的 select a select b.another field from b where a.id b.aid another field from a where 1 lim...

mysql 子查詢中 使用 limit

如果sql語句中的子查詢包含limit 例如 select from a where id in select id from b limit 3 會報錯 this version of mysql doesn t yet support limit in all any some subquery...

MySQL中的標量子查詢,列子查詢,行子查詢

標量子查詢,列子查詢,行子查詢都屬於where子查詢,也就是說都寫在where之後 標量子查詢 概念 子查詢得到的結果是乙個資料 一行一列 語法 select from 資料來源 where 條件判斷 select 欄位名 from 資料來源 where 條件判斷 查詢到的結果就只有乙個結果 案例 ...