按原型排序

时间:2011-10-14 20:36:08

标签: php mysql sorting

MySQL字段中有6个可能的键。让我们称他们为类型。通过PHP,我定义了一个名为$ order的数组,并按照我希望它们出现的顺序排列这些类型。

有一个表articles,其中包含一个字段articlestype。任何文章都可以添加0-6种类型。现在,我想要做的是抓住所有文章,并从原型中订购它们。做这个的最好方式是什么?这可以在MySQL中完成,因为我想这会更快吗?如果没有,如何在PHP中完成?

示例:

表:

id     articleId     type
1      3             type1
2      3             type2
3      3             type3
4      3             type4
5      4             type5
6      4             type6
7      5             type5
8      7             type1
9      7             type5

订单:

$order=array('type1','type2','type3','type4','type5','type6');

如何获取$order变量排序的结果?

2 个答案:

答案 0 :(得分:1)

您需要将该数组按到mysql样式的if / case语句中:

$order_by = "ORDER BY CASE";
$pos = 1;
foreach ($order as $clause) {
   $order_by .= " CASE `type`='$clause' THEN " . $pos++;
}
$order_by .= " ELSE " . $pos++;

会生成类似

的内容
ORDER BY CASE
   WHEN `type`='type1' THEN 1
   WHEN 'type`='type2' THEN 2
   ...
   ELSE n

答案 1 :(得分:1)

  

这可以在MySQL中完成,因为我认为这会更快吗?

仅当您允许MySQL使用索引

您可以创建临时表:

$query = "CREATE TABLE IF NOT EXISTS test (
            sort INT NOT NULL AUTO_INCREMENT,
            `type` VARCHAR(20) NOT NULL,
          PRIMARY KEY (sort),
          KEY (`type`, sort)  
          ENGINE=MEMORY (SELECT 1,'other' <<-- see query below.
                   UNION SELECT 2,'type1' <<-- build this part using 
                   UNION SELECT 3,'type2' <<-- Marc B's code.
                   UNION SELECT 4,'type3'
                   UNION SELECT 5,'type4'   
                   UNION SELECT 6,'type5'
                   UNION SELECT 7,'type6' ";

运行此查询。

现在,您可以使用连接链接此查询,并使用test.sort作为排序键:

SELECT t1.id, t1.article_id, COALESCE(t.`type`,'other') as sort_type
FROM table1 t1
LEFT JOIN test t ON (t1.`type` = t.`type`)
WHERE ....
ORDER BY t.sort;                   

此查询将完全编入索引并尽快运行。