简体   繁体   English

如何以特定顺序多次显示mysql记录

[英]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. 1)这是我为简化说明问题而尝试做的简化的示例。 2) I will be doing thousands of these queries. 2)我将进行数千个此类查询。

I have a mysql table like so: 我有一个像这样的mysql表:

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. 同样,我也不想写两次相同的数组(一次用于IN,一次又一次用于ORDER BY),因为我必须编写成千上万个这样的查询。

So the question: How to show mysql records more than once and in a specific order with the least amount of code? 那么问题来了:如何以最少的代码以特定的顺序 多次显示mysql记录?

Thanks for any suggestions! 感谢您的任何建议!

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 SQLFiddle

You can consider inserting those sequences in some (temp) table with an auto_increment column and a column that designates particular sequence. 您可以考虑使用auto_increment列和指定特定序列的列在某些(临时)表中插入这些序列。 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 SQLFIddle

Thanks to @peterm for the answer (with extra php added for others' use) 感谢@peterm的答案(添加了额外的php供其他人使用)

$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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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