相关疑难解决方法(0)

如何在PostgreSQL上添加条件唯一索引

我有一个line_items包含以下列的表:

product_id
variant_id
Run Code Online (Sandbox Code Playgroud)

variant_id 是可以为空的.

这是条件:

  • 如果variant_id为NULL则product_id应该是唯一的.
  • 如果variant_id有一个值,则组合product_idvariant_id应该是唯一的.

这可能在PostgreSQL中吗?

postgresql indexing null

10
推荐指数
1
解决办法
8431
查看次数

带有LIMIT 1的索引ORDER BY

我正在尝试获取表中最近的行.我有一个简单的时间戳created_at索引.当我查询时ORDER BY created_at DESC LIMIT 1,它需要的远远超过我的想象(我的机器上36k行约50ms).

EXPLAIN -ing声称它使用向后索引扫描,但我确认更改索引(created_at DESC)不会改变查询规划器中的简单索引扫描的成本.

如何优化此用例?

运行postgresql 9.2.4.

编辑:

# EXPLAIN SELECT * FROM articles ORDER BY created_at DESC LIMIT 1;
                                                  QUERY PLAN                                                       
-----------------------------------------------------------------------------------------------------------------------
Limit  (cost=0.00..0.58 rows=1 width=1752)
   ->  Index Scan Backward using index_articles_on_created_at on articles  (cost=0.00..20667.37 rows=35696 width=1752)
(2 rows)
Run Code Online (Sandbox Code Playgroud)

sql postgresql indexing sql-order-by postgresql-performance

6
推荐指数
1
解决办法
514
查看次数