Joao Victor
Joao Victor

Reputation: 1171

Two queries or one query with a sub-query inside?

I'm working on some php code, and i stumbled on something like this:

$query1 = "SELECT COUNT(*) FROM TABLE_A";
$query2 = "SELECT field_a,field_b FROM TABLE_A";

I know these queries are the same as:

$query3 = "SELECT (SELECT COUNT(*) FROM TABLE_A), * from TABLE_A";

The number of connections being open, or queries being executed would go down. But it would be, performatically speaking, a better solution?

Upvotes: 2

Views: 116

Answers (1)

Mike Grigorieff
Mike Grigorieff

Reputation: 66

Use directive SQL_CALC_FOUND_ROWS in first query and function FOUND_ROWS() for second query.

SELECT SQL_CALC_FOUND_ROWS, field_a, field_b FROM TABLE_A;

SELECT FOUND_ROWS();

if your queries has LIMIT, FOUND_ROWS() anyway return count of all records that match the query criteria

Upvotes: 1

Related Questions