在MySQL中,我们可以将一个值或一个查询结果保存的一个用户自定义的变量中,然后在后面的语句在应用。
SET定义变量;
SET @var_name := expr [, @var_name = expr ] ....SET @var_name = expr [, @var_name = expr ] ....
注意:①这里用 ":=" or "="都行,但是"="在其他statement语句中有相等的意思,容易混淆,有时也会出错。强烈建议用 ":="。②在语句里,可以直接用@var_name = expr定义用,不提倡这样,相当于不声明直接用。
下面给出一些例子:
简单的定义,显示
mysql> <code><strong>SET @t1=1, @t2=2, @t3</strong>:=<strong>4;</strong></code>mysql> <code>SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;</code>+------+------+------+--------------------+| @t1 | @t2 | @t3 | @t4 := @t1+@t2+@t3 |+------+------+------+--------------------+| 1 | 2 | 4 | 7 | +------+------+------+--------------------+
Someone use them for rank
SET @pos <strong>:= </strong>0; #这里用等号,感觉像是逻辑判断,结果也不对了<br>SELECT @pos:=@pos+1 as rank,name FROM players ORDER BY score DESC;
<strong></strong>
print only the 100th users
<strong>SET</strong> @counter:=0;<strong>SELECT</strong> users.*<strong>FROM</strong> users<strong>HAVING</strong> (@counter:=@counter+1)%100=0<strong>ORDER BY</strong> user_id; |
保存查询结果值value:
SELECT @total := COUNT(*) FROM table_name; # simicolon 分割连个语句SELECT table_name.id COUNT(*) AS 'count', COUNT(*) / <strong>(SELECT @total)</strong> AS percent FROM table_name,WHERE 1=1GROUP BY YEAR(birthday)ORDER BY YEAR(birthday)
注意上面这个SQL语句看起来逻辑清晰,但与下面的语句执行效果和时间都一样(可能MySQL内部优化了)
SELECT table_name.id COUNT(*) AS 'count', COUNT(*) / <strong>(SELECT </strong>
COUNT(*)
FROM
table_name) AS percent
FROM table_name,WHERE 1=1GROUP BY YEAR(birthday)ORDER BY YEAR(birthday)
其他一些例子:
http://www.mysqldiary.com/user-defined-variables/
疑问:
这里的变量只能保存一个结果值,如何才能临时保存一个select出的结果集呢。
当然简单的方法是创建表/视图; 或者临时表 ,还有好的方法呢? 待研究。
DECLARE声明变量,然后在赋值
DECLARE @var_name var_type
这里举个例子:
<strong>例1:</strong>
DECLARE @total INT DECLARE @total_distinct INTSELECT @total:=COUNT(lice_no) #using ":=" notationFROM table_name; SELECT @total_distinct:=COUNT( DISTINCT lice_no) #using ":=" noationsFROM table_name; SELECT @total - @total_distinct
<strong>例2:</strong>
DECLARE @register_count INT;DECLARE @total_count INT;SELECT @register_count := COUNT(1) FROM t1 WHERE id > 10 ;
SELECT @total_count := COUNT(1) FROM t1 ; SELECT (@register_count * @total_count) AS ratio2
DECLARE 与 SET 区别:
<ol> <li>DECLARE 必须指定类型,而SET是不用的</li> <li>SET定义的是用户自定义变量,是Session Sensitive 的; DECLARE 声明的变量一般为局部变量,其有效区间是声明的函数或存储过程中。</li> <li>定义全局变量应该为 SET GLOBAL @var_name 后者SET @@GLOBAL.var_name</li> </ol>
注意及附录:
这里关于变量的使用范围要清楚。官方介绍网址: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
mySqlStringTypesimpactStorageAndPerformanCeaseAsfollows:1)長度,始終使用theSamestoragespace,whatcanbefasterbutlessspace-felfficity.2)varCharisvariable varcharisvariable length,morespace-morespace-morespace-effficitybuteftife buteftife butfority butfority textifforlyslower.3)

mysqlStringTypesIncludeVarChar,文本,char,Enum和set.1)varCharisVersAtileForvariable-lengthStringStringSuptoPuptOuptoPepePecifiedLimit.2)textisidealforlargetStortStorStoverStoverStorageWithoutAutAdefinedLength.3)charlisfixed-lenftenge,for forConsistentDatalikeCodes.4)

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

toadduserInmysqleffect和securly,跟隨台詞:1)USEtheCreateUserStattoDaneWuser,指定thehostandastrongpassword.2)GrantNecterAryAryaryPrivilegesSustherthing privilegesgeStatement,usifementStatement,adheringtotheprinciplelastprefilegege.3)

toaddanewuserwithcomplexpermissionsinmysql,loldtheSesteps:1)創建eTheEserWithCreateuser'newuser'newuser'@''localhost'Indedify'pa ssword';。 2)GrantreadAccesstoalltablesin'mydatabase'withGrantSelectOnMyDatabase.to'newuser'@'localhost';。 3)GrantWriteAccessto'

MySQL中的字符串數據類型包括CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT,排序規則(Collations)決定了字符串的比較和排序方式。 1.CHAR適合固定長度字符串,VARCHAR適合可變長度字符串。 2.BINARY和VARBINARY用於二進制數據,BLOB和TEXT用於大對像數據。 3.排序規則如utf8mb4_unicode_ci忽略大小寫,適合用戶名;utf8mb4_bin區分大小寫,適合需要精確比較的字段。

最佳的MySQLVARCHAR列長度選擇應基於數據分析、考慮未來增長、評估性能影響及字符集需求。 1)分析數據以確定典型長度;2)預留未來擴展空間;3)注意大長度對性能的影響;4)考慮字符集對存儲的影響。通過這些步驟,可以優化數據庫的效率和擴展性。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

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

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver CS6
視覺化網頁開發工具