10

I have this database query

SELECT *
FROM (`metadata` im)
INNER JOIN `content` ic ON `im`.`rev_id`  = `ic`.`rev_id`
WHERE `im`.`id` = '00039'
AND `current_revision` = 1
ORDER BY `timestamp` DESC
LIMIT 5, 5 

The query limits the total rows in the result to 5. I want to limit the left table metadata to 5 without limiting the entire result-set.

How should I write the query?

Mr Hyde
  • 3,393
  • 8
  • 36
  • 48

3 Answers3

17

If you think about what you are trying to do, you're not really doing a select against metadata.

You need to sub query that first.

Try:

SELECT *
FROM ((select * from metadata limit 5) im)
INNER JOIN `content` ic ON `im`.`rev_id`  = `ic`.`rev_id`
WHERE `im`.`id` = '00039'
AND `current_revision` = 1
ORDER BY `timestamp` DESC
Christian Payne
  • 7,081
  • 5
  • 38
  • 59
0

Here is another possible approach:

SET @serial=0;
SET @thisid=0;

SELECT 
   @serial := IF((@thisid != im.id), @serial + 1, @serial), 
   @thisid := im.id,
   * 
FROM (`metadata` im)
WHERE `im`.`id` = '00039'
AND `current_revision` = 1
AND @serial < 5
ORDER BY `timestamp` DESC

This isn't tested. Please let me know if you run into issue implementing this - and I can elaborate.

Bas Kuis
  • 748
  • 1
  • 7
  • 20
0

Well, I think you mean LEFT JOIN try using LEFT JOIN instead of INNER JOIN

    SELECT DISTINCT *
    FROM (`metadata` im)
    INNER JOIN `content` ic ON `im`.`rev_id`  = `ic`.`rev_id`
    WHERE `im`.`id` = '00039'
    AND `current_revision` = 1
    ORDER BY `timestamp` DESC
    LIMIT 5, 5 
S L
  • 14,262
  • 17
  • 77
  • 116
  • Tried that! Not what I want. A left join will incude any records in `left` table that dont have counterparts in the right table. An inner join will include only those records common to both – Mr Hyde Feb 26 '11 at 12:10
  • Though I don't recommend mine – S L Feb 26 '11 at 12:24