0

想象一个简单的情况,您要么是designerdeveloper要么reviewer存储在work这样的表中:

+----+----------+-----------+----------+
| id | designer | developer | reviewer |    
+----+----------+-----------+----------+
| 1  | sudo_O   | fred      | bob      |
| 2  | fred     | bob       | sudo_O   |
| 3  | bob      | sudo_O    | fred     |
| 4  | sudo_O   | fred      | bob      |
| 5  | bob      | sudo_O    | fred     |
| 6  | fred     | bob       | sudo_O   |  
| 7  | fred     | bob       | john     |   
| 8  | john     | bob       | fred     | 
+----+----------+-----------+----------+

要查询表以查找我的所有工作将是:

select * from work where designer='sudo_O' or developer='sudo_O' or reveiwer ...

是否可以按工作类型(设计、开发、审查)对结果进行排序,如下所示:

1, sudo_O, fred, bob
4, sudo_O, fred, bob
3, bob, sudo_O, fred
5, bob, sudo_O, fred
2, fred, bob, sudo_O
6, fred, bob, sudo_O

这就是我的所有设计工作首先展示,然后是开发,然后是审查。

4

1 回答 1

3
SELECT id, designer, developer, reviewer
FROM work 
WHERE designer = 'sudo_O' OR developer = 'sudo_O' OR reviewer = 'sudo_O'
ORDER BY 
    CASE 'sudo_O' 
        WHEN designer  THEN 1
        WHEN developer THEN 2
        WHEN reviewer  THEN 3
    END, id ;

或者像这样(在大表上可能更有效,并且有 3 个索引,每列一个):

SELECT id, designer, developer, reviewer
FROM 
  ( SELECT id, designer, developer, reviewer, 1 AS ord
    FROM work 
    WHERE designer = 'sudo_O' 
  UNION ALL
    SELECT id, designer, developer, reviewer, 2
    FROM work 
    WHERE developer = 'sudo_O' 
  UNION ALL
    SELECT id, designer, developer, reviewer, 3
    FROM work 
    WHERE reviewer = 'sudo_O'
  ) AS t
ORDER BY ord, id ;
于 2013-05-09T10:51:11.137 回答