I'm trying to sort by certain alphanumeric range 1-3 & A-B for first 15 matches, but am getting nothing in output. Using MeekroDB. Not sure how to translate what I have here to their method.
$results = DB::query("SELECT substr(theme, 1, 1) as Alphabet
FROM gallery ORDER BY (CASE theme
WHEN '1%' THEN 1
WHEN '2%' THEN 2
WHEN '3%' THEN 3
WHEN 'A%' THEN 4
WHEN 'B%' THEN 5
ELSE -1
END) LIMIT 15");
$x = 0
foreach ($results as $row) {
$x++;
if ($x == 1) { // first in query
$t1 = $row['theme'];
$d1 = $row['developer'];
$th1 = $row['thumb'];
$thlg1 = $row['thumb_lg'];
}
...
}
Echo example in body:
<img src="<?php echo($th1); ?>" data-retina="<?php echo($thlg1); ?>" alt="<?php echo($t1); ?>" />
<span><p class="hname"><?php echo($t1); ?></p>
<p class="hdev"><?php echo($d1); ?></p></span>
Update2:
$results = DB::query("SELECT substr(theme, 1, 1) as Alphabet, theme, developer, thumb, thumb_lg
FROM gallery ORDER BY (CASE
WHEN theme LIKE '1%' THEN 1
WHEN theme LIKE '2%' THEN 2
WHEN theme LIKE '3%' THEN 3
WHEN theme LIKE 'A%' THEN 4
WHEN theme LIKE 'B%' THEN 5
ELSE -1
END) LIMIT 15");
Update3:
$results = DB::query("SELECT substr(theme, 1, 1) as Alphabet, theme, developer, thumb, thumb_lg FROM gallery
ORDER BY (CASE Alphabet
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN 'A' THEN 4
WHEN 'B' THEN 5
ELSE 6
END)
LIMIT 15");
The ORDER BY
clause should be:
ORDER BY CASE Alphabet
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN 'A' THEN 4
WHEN 'B' THEN 5
ELSE 6
END, theme
Your code is doing exact matches on the whole theme, '1%' should have been matched using LIKE
. My version just uses the first character, which you already extracted into Alphabet
.
Another way to write this is:
ORDER BY IF(LOCATE(Alphabet, "123AB"), 0, 1), theme
This works because the order of your first characters matches the normal lexicographic order.