user1218478
user1218478

Reputation: 27

How to show mysql records more than once and in a specific order

1) This is a much simplified example of what I am trying to do for ease of explaining the problem. 2) I will be doing thousands of these queries.

I have a mysql table like so:

NUMBER   TEXTCOLOUR
one      green
two      red
three    orange
four     pink

I want to display the following (each word having a different textcolour), in this order:

three two one three

I have tried:

$query = "SELECT * FROM `table` WHERE `number` IN ('three', 'two', 'one','three') 
ORDER BY FIND_IN_SET(number, 'three,two,one,three')";

$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "
<div class='" .$textcolour. "'>$number</div>
";
}   

but this will not display the record 'three' more than once. Also I don't want to have to write the same array twice (once for IN and again for the ORDER BY) as I have to write thousands of these queries.

So the question: How to show mysql records more than once and in a specific order with the least amount of code?

Thanks for any suggestions!

Upvotes: 2

Views: 213

Answers (2)

user1218478
user1218478

Reputation: 27

Thanks to @peterm for the answer (with extra php added for others' use)

$result = mysql_query("SELECT b.textcolour FROM (
SELECT 'three' number UNION ALL 
SELECT 'two' UNION ALL 
SELECT 'one' UNION ALL 
SELECT 'three'
) a LEFT JOIN table1 b ON a.number = b.number"); 

while ($row = mysql_fetch_object($result))

Upvotes: 0

peterm
peterm

Reputation: 92785

Try

SELECT b.textcolour
  FROM 
(SELECT 'three' number UNION ALL 
 SELECT 'two' UNION ALL 
 SELECT 'one' UNION ALL 
 SELECT 'three') a LEFT JOIN table1 b ON a.number = b.number

Output:

| TEXTCOLOUR |
--------------
|     orange |
|        red |
|      green |
|     orange |

SQLFiddle

You can consider inserting those sequences in some (temp) table with an auto_increment column and a column that designates particular sequence. Then you can just do

SELECT b.textcolour
  FROM sequences a JOIN colours b
    ON a.number = b.number
 WHERE a.seq_no = ?
 ORDER BY a.id

SQLFIddle

Upvotes: 1

Related Questions