按两列中的一个对查询结果进行排序

huangapple go评论91阅读模式
英文:

order result of query by on of two columns

问题

我有这个表:

  1. CREATE TABLE Foo
  2. (
  3. id_key INTEGER PRIMARY KEY,
  4. key1 INTEGER NOT NULL,
  5. seq_num1 INTEGER NOT NULL,
  6. key2 INTEGER,
  7. seq_num2 INTEGER,
  8. data BLOB NOT NULL
  9. );

而我想选择匹配 key1key2data,这很简单:

  1. SELECT data
  2. FROM Foo
  3. WHERE (key1 = ? OR key2 = ?)

但是接下来,我想根据在表的行中匹配的内容 - key1key2,对此查询的结果进行排序。

我认为这样的写法应该可以工作:

  1. SELECT data
  2. FROM Foo
  3. WHERE (key1 = ? OR key2 = ?)
  4. ORDER BY
  5. CASE
  6. WHEN key1 = ?
  7. THEN seq_num1
  8. ELSE seq_num2
  9. END

但我不确定这是否是最佳解决方案?因为在这个查询中,我对 key1 进行了两次比较,而只需要比较一次。

我使用的是 sqlite3。

英文:

I have this table:

  1. CREATE TABLE Foo
  2. (
  3. id_key INTEGER PRIMARY KEY,
  4. key1 INTEGER NOT NULL,
  5. seq_num1 INTEGER NOT NULL,
  6. key2 INTEGER,
  7. seq_num2 INTEGER,
  8. data BLOB NOT NULL
  9. );

And I want to select data where key1 or key2 match,
this is simple:

  1. SELECT data
  2. FROM Foo
  3. WHERE (key1 = ? OR key2 = ?)

but then I want to order results of this query by seq_num1 or seq_num2, depending on what matched in the table's row - key1 or key2 respectively.

I think that something like this should work:

  1. SELECT data
  2. FROM Foo
  3. WHERE (key1 = ? OR key2 = ?)
  4. ORDER BY
  5. CASE
  6. WHEN key1 = ?
  7. THEN seq_num1
  8. ELSE seq_num2
  9. END

but I'm not sure is this optimal solution? Because of in this query I compare key1 twice, while it should be enough compare once.

I use sqlite3.

答案1

得分: 1

这是否是您想要的?我不使用SQLite,但这个MySQL命令似乎被SQLite理解。

  1. select
  2. data, seq_num1 as seq
  3. from Foo
  4. where key1 = ?
  5. union
  6. select
  7. data, seq_num2 as seq
  8. from Foo
  9. where key2 = ?
  10. order by seq;
英文:

Could this be what you want? I don't use sqlite, but this mysql command seems to be understood by sqlite.

  1. select
  2. data, seq_num1 as seq
  3. from Foo
  4. where key1 = ?
  5. union
  6. select
  7. data, seq_num2 as seq
  8. from Foo
  9. where key2 = ?
  10. order by seq;

huangapple
  • 本文由 发表于 2023年2月19日 03:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定