从按列值排序的表中获取记录

时间:2019-04-04 09:52:29

标签: mysql sql

我有一个带有列的表,用于维护记录的状态。即

const categories = ['cat1', 'cat2', 'cat3'];
const questions = Array.from({ length: 10 }, (_, i) => (
  { _id: i, question: `question ${i}`, answer: `answer ${i}`, category: categories[Math.floor(Math.random() * categories.length)]})
);
  
function randomQuestions(questions, categories, n) {
  // group the ids into arrays for each category asked
  const idsByCategories = questions.reduce((acc, x) => {
    if (categories.includes(x.category)) {
      acc[x.category] = [...(acc[x.category] || []), x._id];
    }
    return acc;
  }, {});
  // pick a number of random ids for each category
  return categories.map(cat => (idsByCategories[cat] || []).sort(() => 0.5 - Math.random()).slice(0, n));
}

console.log(JSON.stringify(randomQuestions(questions, ['cat1', 'cat3'], 2)));

console.log(questions);

我想按“打开”后跟“完成”的顺序获取记录。我可以使用一个SQL查询完成此操作吗?如果是这样,我应该怎么写?

2 个答案:

答案 0 :(得分:2)

是的,您可以使用ORDER BY语句和FIELD函数来做到这一点:

SELECT * FROM table1 ORDER BY FIELD(state, 'Open', 'Complete')

答案 1 :(得分:0)

尝试这样的事情:

select * 
from table_name 
order by decode (state, 'Open', 1, 'Complete', 2, 3)