如何在IndexedDB中对重复项进行分组

时间:2016-03-17 15:36:03

标签: indexeddb

我如何为indexedDB构建这样的查询:

SELECT GROUP_CONCAT(id) as ids FROM contacts GROUP BY name HAVING count(name) > 1 

我的目标是展示重复的项目。

1 个答案:

答案 0 :(得分:5)

您必须手动迭代,但使用索引按名称进行迭代:

在你需要的升级中#34;处理程序:

// Assumes records like {id: 1234, name: 'Beyoncé'}
var store = db.createObjectStore('contacts', {keyPath: 'id'});
var index = store.createIndex('by_name', 'name');

查询:

// Results end up here - this is map from name to array-of-ids:
var dupes = new Map();

var tx = db.transaction('contacts');
var index = tx.objectStore('contacts').index('by_name');
var req = index.openCursor();
var last;
req.onsuccess = function() {
  var cursor = req.result;

  if (!cursor) return; // Done!

  var name = cursor.key, id = cursor.primaryKey;

  if (name === last) {
    // It's a duplicate!
    if (!dupes.has(name)) dupes.set(name, []);
    dupes.get(name).push(id);
  } else {
    last = name;
  }
  cursor.continue();
};