views:

45

answers:

3

Below is an over-simplified version of table I'm using:

fruits
+-------+---------+ 
| id    | type    | 
+-------+---------+ 
| 1     | apple   | 
| 2     | orange  | 
| 3     | banana  | 
| 4     | apple   | 
| 5     | apple   | 
| 6     | apple   | 
| 7     | orange  | 
| 8     | apple   | 
| 9     | apple   | 
| 10    | banana  | 
+-------+---------+ 

Following are the two queries of interest:

SELECT * FROM fruits WHERE type='apple' LIMIT 2;

SELECT COUNT(*) AS total FROM fruits WHERE type='apple'; // output 6

I want to combine these two queries so that the results looks like this:

+-------+---------+---------+  
| id    | type    | total   |
+-------+---------+---------+  
| 1     | apple   | 6       |
| 4     | apple   | 6       | 
+-------+---------+---------+

The output has to be limited to 2 records but it should also contain the total number of records of the type apple.

How can this be done with 1 query?

A: 

Sounds like a UNION of the first two queries and select from the UNION with a LIMIT.

chibacity
+1  A: 

You should use SQL_CALC_FOUND_ROWS for that.

SELECT SQL_CALC_FOUND_ROWS * FROM fruits WHERE type='apple' LIMIT 2;

will return the IDs of your apples, and remember how much it would have returned without the LIMIT clause

SELECT FOUND_ROWS();

will return how many apples would have been found, without the limit statement.

Konerak
You should put the SQL_CALC_FOUND_ROWS in conditional-comments though, to allow graceful failing on SQL-servers that don't support it.
Konerak
+2  A: 
SELECT *, (SELECT COUNT(*) AS total FROM fruits WHERE type='apple') AS Total 
FROM fruits WHERE type='apple' LIMIT 2;

Depending on how MySQL interprets it, it may cache the inner query so that it doesn't have to reevaluate it for every record.

Another way to do it is with a nested query and a join (this would be useful it you need more than one fruit type, for example):

SELECT fruits.*, counts.total
FROM fruits 
  INNER JOIN (SELECT type, COUNT(*) AS total FROM fruits GROUP BY type) counts ON (fruits.type = counts.type)
WHERE fruits.type='apple'
LIMIT 2;
Senseful
Hey @Lost, aren't your current 2 queries way simpler than this monster? ;)
Col. Shrapnel
@col: Well maybe. But I was curious to learn to do this with 1 query. And yes, though it may not look pretty, I prefer to use 1 query instead of 2.
Yeti
@Lost and you'll be wrong. There is not a single benefit in doing it with one.
Col. Shrapnel
@col: hah, this query is a cake walk... take a look at one of these beasts I recently wrote: http://stackoverflow.com/questions/2938427/converting-delimited-string-to-multiple-values-in-mysql/2938522#2938522 http://stackoverflow.com/questions/2776632/how-to-return-result-set-based-on-other-rows/2777221#2777221
Senseful
@Lost you, you got wrong even more. Nothing to boast about.
Col. Shrapnel
@Col Thanks...!
Yeti