Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

mysql - an efficient way to test if a table row exists

I'm trying to find the most efficient way to determine if a table row exists.

I have in mind 3 options:

  1. SELECT EXISTS(SELECT 1 FROM table1 WHERE some_condition);

  2. SELECT 1 FROM table1 WHERE some_condition LIMIT 0,1;

  3. SELECT COUNT(1) FROM table1 WHERE some_condition;

It seems that for MySQL the first approach is more efficient: Best way to test if a row exists in a MySQL table

Is it true in general for any database?

UPDATE:

I've added a third option.

UPDATE2:

Let's assume the database products are mysql, oracle and sql-server.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you mean to use as a test if AT LEAST ONE row exists with some condition (1 or 0, true or false), then:

select count(1) from my_table where ... and rownum < 2;

Oracle can stop counting after it gets a hit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...