0

I have this table:

enter image description here

and I'd like to select the rows between 'inizio_votazione1' e fine_votazione1'.

I tried this code:

$sql  = "SELECT codice FROM scansioni WHERE codice BETWEEN 'inizio_votazione1' 
AND 'fine_votazione1'";

while ($row = $result->fetch_row()) {
// print_r($row);

$res = $row[0];
echo $res;
echo "<br />";
}

but I see no result.

Which is the correct syntax to retrieve the desired result? Thanks

3
  • how dynamic does this have to be? If it is always those records you want I would run a between on your id field instead: WHERE id BETWEEN 1 AND 9 Commented May 2, 2017 at 16:55
  • do you want all rows between these value? Commented May 2, 2017 at 16:58
  • It's dynamic because are runtime votes, so I thought to find the way to mark each votation inserting a record with "inizio('begin')" and "fine('end')" Commented May 2, 2017 at 17:07

4 Answers 4

1

I don't think you really want to use BETWEEN. That will basically look for alphabetically ordered values that are between those two. I would think you could do something like this:

SELECT codice
FROM scansioni
WHERE id > (SELECT MIN(id) 
            FROM scansioni
            WHERE codice IN ('inizio_votazione1', 'fine_votazione1'))
  AND id < (SELECT MAX(id) 
            FROM scansioni
            WHERE codice IN ('inizio_votazione1', 'fine_votazione1'))

This may not be the most elegant solution, but from what I tried, it worked.

A better option might be to add a separate table that stores the start and end id for each group. Then you could just get the start and end ids for the group you want and then select all the values from scansioni that have ids in the correct range.

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

1 Comment

You are right. I hadn't tried the solution in MySQL. I just changed my answer so that it should work for MySQL.
0

Try this:

SELECT codice FROM scansioni WHERE codice between 'inizio_votazione1' abd 'fine_votazione1'

Comments

0

Try changing:

$sql  = SELECT codice FROM scansioni WHERE codice BETWEEN 'inizio_votazione1' 
AND 'fine_votazione1';

To:

$sql  = "SELECT codice FROM scansioni WHERE codice BETWEEN 'fine_votazione1' 
AND 'inizio_votazione1'";

BETWEEN uses the sort order to determine the result.

Also, strings need to be quoted in php.

1 Comment

You're right, but I just mistyped when I wrote the question, sorry
0

Try this:-

SELECT codice FROM `scansioni` WHERE id between (select id from scansioni where codice='inizio_votazione1') and (select id from scansioni where codice='fine_votazione1')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.