0

Here an example Table:

+--------+------------+
| itemID | itemvalue  |
+--------+------------+
|      1 |          a |
|      2 |          b |
|      3 |          a |
|      4 |          a |
|      5 |          b |
|      6 |          a |
|      7 |          b |
|      8 |          a |
|      9 |          a |
|     10 |          b |
+--------+------------+

I like to know how many 'a' are in the first 5 rows of the table. So in words should do the following:

Select only the first 5 rows from table X WHERE itemvalue = a

This should return rows 1, 3 and 4

Is it possible to do this with just a Mysql Query and without further computing?

1
  • Do you mean the first 5 rows orderd by itemID? Commented Jul 26, 2021 at 8:43

3 Answers 3

4

You can try with using an inner join query to do it

select t1.* from my_table t1
join
(select itemId from my_table order by itemId limit 5) t2
on t1.itemID=t2.itemID
where t1.itemvalue='a'

Working demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help but the result is: MySQL Error: This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery. My MySQL Version is 8.0.25. But radocaws Soluition worked for my as well.
1

Here's one idea:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(itemID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,itemvalue CHAR(1) NOT NULL
);

INSERT INTO my_table VALUES
( 1,'a'),
(2,'b'),
(3,'a'),
(4,'a'),
(5,'b'),
(6,'a'),
(7,'b'),
(8,'a'),
(9,'a'),
(10,'b');

...

 WITH cte AS
 (
 SELECT *
      , ROW_NUMBER() OVER (ORDER BY itemid) x 
   FROM my_table
 )
 SELECT itemID,itemvalue FROM cte WHERE x <=5 AND itemvalue = 'a';
 +--------+-----------+
 | itemID | itemvalue |
 +--------+-----------+
 |      1 | a         |
 |      3 | a         |
 |      4 | a         |
 +--------+-----------+

1 Comment

You're in good company, because neither do I! However, further insight can be gained by executing the 'cte' bit on its own.
-1
  SELECT * FROM table X WHERE itemvalue = a LIMIT $startingOffset, $count"

here in your case count is 5 and pass starting offset. if u pass 10 as starting offset it will fetch first 5 rows with starting index of 11

1 Comment

That would just give you all a rows until the limit is reached. The question was how to check if the first 5 rows have the value a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.