SELECT EXISTS(SELECT /p2/ FROM table WHERE id = 1)
SELECT /p2/ FROM table WHERE id = 1 LIMIT 1
COUNT(id)
id
fetchColumn()
rowCount()
From the following 3 Parts, What is the best method to check if a row exists or not with and without the ability to retrieve data like.
/Query/ SELECT id FROM table WHERE id = 1 LIMIT 1
/Function/ rowCount()
/Query/ SELECT EXISTS(SELECT COUNT(id) FROM table WHERE id = 1)
/Function/ fetchColumn()
In your opinion, What is the best way to do that?
By best I guess you mean consuming the least resources on both MySQL server and client.
That is this:
SELECT COUNT(*) count FROM table WHERE id=1
You get a one-row, one-column result set. If that column is zero, the row was not found. If the column is one, a row was found. If the column is greater that one, multiple rows were found.
This is a good solution for a few reasons.
COUNT(*)
is decently efficient, especially if id
is indexed. Adding LIMIT 1
will do nothing if added to this query. It is already a one-row result set, inherently. You can add it, but then you'll make the next person looking at your code wonder what you were trying to do, and wonder whether you made some kind of mistake.
COUNT(*)
counts all rows that match the WHERE
statement. COUNT(id)
is slightly slower because it counts all rows unless their id
values are null. It has to make that check. For that reason, people usually use COUNT(*)
unless there's some chance they want to ignore null values. If you put COUNT(id)
in your code, the next person to work on it will have to spend some time figuring out whether you meant anything special by counting id
rather than *
.
You can use either; they give the same result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.