简体   繁体   中英

is that possible to count how many rows between two rows mysql?

I have a mysql table like below. I want to count how many rows between berry and strawberry, in my case is 2 rows between these two fruits. How can I achieve that?

 id fruit 1 apple 2 berry 3 banana 4 pineapple 5 strawberry 

Try this query,

  $sql = "SELECT COUNT(*) as total_count FROM table_name JOIN ( SELECT MAX(id) as 
  maxid,MIN(id) as minid FROM `table_name` WHERE fruit = 'berry' OR 
  fruit= 'strawberry') as temp ON table_name.id > temp.minid AND 
  table_name.id<temp.maxid";

you can write query similar to this-

$sql = select * from table where fruit between 'berry' and 'strawberry';
$result = mysql_query($sql);
$rows =  mysql_num_rows($result);

here is the reference- SQL Between clause with strings columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM