MySQL 中的 FOUND_ROWS() 與 ROW_COUNT() 函數

移植sql server 的存儲過程到mysql中,遇到了sql server中的:html

IF @@ROWCOUNT < 1mysql

對應到mysql中可使用 FOUND_ROWS() 函數來替換。sql

1. found_rows() 函數mybatis

文檔地址:http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_found-rowsoracle

1)found_rows() 的第一種使用狀況(帶有SQL_CALC_FOUND_ROWS,也帶 limit):app

A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:ide

mysql> 
    -> 
mysql> 
SELECT SQL_CALC_FOUND_ROWS * FROM tbl_nametbl_nameWHERE id > 100 LIMIT 10;SELECT FOUND_ROWS();

The second SELECT returns a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause.函數

前面的帶有limit的select語句若是加上了 SQL_CALC_FOUND_ROWS,那麼接下來執行的 SELECT FOUND_ROWS(); 將返回前面語句不帶limit語句返回的行數
this

此種狀況下,select found_rows() 和 select count(*) 有一個很小的區別:若是userId容許爲null,那麼select found_rows() 的結果可能要比select count(*) 要小一些。由於前者等價於:select count(userId) from Users; 而該語句不會計算userId 爲null的行在內。而count(*)會計算在內。url

2)found_rows() 的第二種/第三中使用狀況(帶有SQL_CALC_FOUND_ROWS):

In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful SELECT statement, FOUND_ROWS() returns the number of rows in the result set returned by that statement. If the statement includes a LIMIT clause, FOUND_ROWS() returns the number of rows up to the limit. For example, FOUND_ROWS() returns 10 or 60, respectively, if the statement includes LIMIT 10 or LIMIT 50, 10.

The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement. If you need to refer to the value later, save it:

mysql> 
mysql> 
SELECT SQL_CALC_FOUND_ROWS * FROM ... ;SET @rows = FOUND_ROWS();

If you are using SELECT SQL_CALC_FOUND_ROWS, MySQL must calculate how many rows are in the full result set. However, this is faster than running the query again without LIMIT, because the result set need not be sent to the client.

1> 第二種使用狀況(帶有SQL_CALC_FOUND_ROWS,也沒有帶 limit ):

若是前面的select語句沒有帶 SQL_CALC_FOUND_ROWS,也沒有帶 limit ,那麼後面的 SELECT FOUND_ROWS(); 返回的結果就是前面的select返回的行數;

2> 第三中使用狀況(帶有SQL_CALC_FOUND_ROWS,可是有帶 limit ):

若是前面的select語句沒有帶 SQL_CALC_FOUND_ROWS,可是帶有 limit,那麼後面的 SELECT FOUND_ROWS(); 返回的結果就是limit語句到達的最大的行數,好比:select * from xxx limit 10; 到達的最大的行數爲10,因此 found_rows() 返回10;好比 select * from xxx limit 50,10; 它要從第50行開始,再掃描10行,因此到達的最大的行數爲60,因此found_rows() 返回60。

這裏第一個select found_rows() 返回105,由於他是從偏移100的地方,再掃描5行,因此返回105;可是第二個掃描的結果爲空,select found_rows()返回了0!而不是105,由於 where userId=999999的結果爲空,因此後面的 limit 100,5根本就沒有執行因此select found_rows()返回了0

再看一個例子,更深刻的理解其中狀況下的 found_rows():

上面sql中 user_Pwd=xx 的值都是同樣的。能夠看到這種狀況下的found_rows() 是對的select語句的中間結果,再 limit 時,此時的limit的掃描到的最大的行數。和原始表中的數據的行數,是沒有關係的。他是對select的中間結果的limit,而後才獲得最後的結果集,再返回。

3)SQL_CALC_FOUND_ROWS and FOUND_ROWS() 適合使用的場景

SQL_CALC_FOUND_ROWS and FOUND_ROWS() can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again. An example is a Web script that presents a paged display containing links to the pages that show other sections of a search result. Using FOUND_ROWS() enables you to determine how many other pages are needed for the rest of the result.

1> SQL_CALC_FOUND_ROW + limit + found_rows() 可使用在分頁的場合。

2> 不帶SQL_CALC_FOUND_ROW 的 found_rows() 可使用在存儲過程當中判斷前面的select是否爲空

DELIMITER //
DROP PROCEDURE IF EXISTS loginandreg //

CREATE PROCEDURE loginandreg(
    OUT userId     BIGINT,
    IN user_Pwd                          VARCHAR(32),
    IN user_MobileCode                   VARCHAR(16),
    IN user_RegIP                        VARCHAR(16)
)
BEGIN
IF EXISTS(SELECT * FROM Users u WHERE u.user_MobileCode=user_MobileCode) THEN
    SELECT u.userId INTO userId FROM Users u WHERE u.user_MobileCode=user_MobileCode AND u.user_Pwd=user_Pwd;    
    IF FOUND_ROWS() < 1 THEN
        SELECT -1 INTO userId;
    END IF;
ELSE 
    INSERT INTO Users(user_Pwd,user_MobileCode,user_Visibility,user_Level,user_RegTime,user_RegIP,user_Collecter,user_Collected)
    VALUES (user_Pwd,user_MobileCode,6,6,NOW(),user_RegIP,0,0);
    SELECT LAST_INSERT_ID() INTO userId;
END IF;

END //
DELIMITER ;

上面存儲過程當中的:

SELECT u.userId INTO userId FROM Users u WHERE u.user_MobileCode=user_MobileCode AND u.user_Pwd=user_Pwd;    
    IF FOUND_ROWS() < 1 THEN
        SELECT -1 INTO userId;
    END IF;

就是一個很好的使用的例子。

這種存儲過程的場景中就可使用 mysql 的 FOUND_ROWS() 替換 sql server 存儲過程當中的 IF @@ROWCOUNT < 1 語句

--------------------------------------------------------------------------------------------------------------------------

2. row_count() 函數

文檔地址:http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_row-count

一句話,row_count() 函數通常用於返回被 update, insert, delete 實際修改的行數

In MySQL 5.6, ROW_COUNT() returns a value as follows:

  • DDL statements: 0. This applies to statements such as CREATE TABLE or DROP TABLE.

  • DML statements other than SELECT: The number of affected rows. This applies to statements such as UPDATE, INSERT, or DELETE (as before), but now also to statements such as ALTER TABLE and LOAD DATA INFILE.

  • SELECT: -1 if the statement returns a result set, or the number of rows affected」 if it does not. For example, for SELECT * FROM t1, ROW_COUNT() returns -1. For SELECT * FROM t1 INTO OUTFILE 'file_name', ROW_COUNT() returns the number of rows written to the file.

  • SIGNAL statements: 0.

For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows found」; that is, matched by the WHERE clause.

也就是說對於update語句,row_count() 默認返回的是實際被修改的行數;可是經過參數設置,也能夠返回找到的行數(或者說匹配的行數,受影響的行數),這樣設置就能兼容於Oracle  ps/sql中 sql%rowcount 和 sql server 中的 @@RowCount

可是 row_count() 的結果和 mysql 的JDBC driver的默認行爲倒是不一致的,mysql jdbc中的 Statement.getUpdateCount() 函數返回的是被找到的行數,而不是實際被修改的行數,若是要返回被實際修改的行,應該使用存儲過程,相關連接說明:

http://stackoverflow.com/questions/17544782/how-to-tell-number-of-rows-changed-from-jdbc-execution

http://mybatis-user.963551.n3.nabble.com/Return-number-of-changed-rows-td3888464.html#a3903155

http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html (這裏包含了全部mysql jdbc 連接可設置的參數)

useAffectedRows
Don't set the CLIENT_FOUND_ROWS flag when connecting to the server (not JDBC-compliant, will break most applications that rely on "found" rows vs. "affected rows" for DML statements), but does cause "correct" update counts from "INSERT ... ON DUPLICATE KEY UPDATE" statements to be returned by the server.

Default: false
Since version: 5.1.7 

該參數默認爲false,咱們最好不要進行修改,若是修改了就和JDBC標準不兼容!若是須要返回實際被修改的行,應該使用存儲過程(使用row_count())

If you need to know how many records were *changed* (not that same as the number matching the where) then you might consider a stored
procedure.

可是設置 useAffectedRows=true; 有一個好處,就是它能正確的返回 insert ... on duplicate key update 的結果(若是不設置爲true,返回的結果是錯誤的):參見:http://blog.sina.com.cn/s/blog_7325f5150101i3v4.html

mysql jdbc url 另外兩個重要的參數 userUnicode 和 characterEncoding

useUnicode
Should the driver use Unicode character encodings when handling strings? Should only be used when the driver can't determine the character set mapping, or you are trying to 'force' the driver to use a character set that MySQL either doesn't natively support (such as UTF-8), true/false, defaults to 'true' Default: true Since version: 1.1g
characterEncoding
If 'useUnicode' is set to true, what character encoding should the driver use when dealing with strings? (defaults is to 'autodetect')
Since version: 1.1g 

userUnicode 參數默認就是true,而characterEncoding默認是自動偵測。因此通常

jdbc:mysql://localhost:3306/dbname?useUnicode=true&amp;characterEncoding=UTF-8

能夠簡化爲:jdbc:mysql://localhost:3306/dbname?characterEncoding=UTF-8

關於對mysql複製的影響:

Important

FOUND_ROWS() is not replicated reliably using statement-based replication. This function is automatically replicated using row-based replication.
Important

ROW_COUNT() is not replicated reliably using statement-based replication. This function is automatically replicated using row-based replication.

注意:found_rows() 和 row_count() 在基於 語句的複製 環境中是不可靠的,它們自動使用 基於行的複製行爲。

3. 總結

1)在存儲過程遷移時, sql server 的 @@RowCount, oracle 的 sql%rowcount 能夠被 mysql 的 found_rows()和row_count()替代;

2)mysql 中的 found_rows() 的三種用法;

3)mysql jdbc url 另外兩個重要的參數 userUnicode 和 characterEncoding;

     mysql jdbc 全部參數參見:http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html

相關文章
相關標籤/搜索