-- 门店多分类关联表（v4.0.9+）
-- 执行：mysql ... < migrate-store-category-link.sql

CREATE TABLE IF NOT EXISTS store_category_link (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  store_id BIGINT UNSIGNED NOT NULL,
  category_id BIGINT UNSIGNED NOT NULL,
  priority INT NOT NULL DEFAULT 0,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  PRIMARY KEY (id),
  UNIQUE KEY uk_store_category_link (store_id, category_id),
  KEY idx_store_category_link_category (category_id),
  CONSTRAINT fk_store_category_link_store FOREIGN KEY (store_id) REFERENCES store_store(id) ON DELETE CASCADE,
  CONSTRAINT fk_store_category_link_category FOREIGN KEY (category_id) REFERENCES common_store_category(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 从现有主分类回填
INSERT IGNORE INTO store_category_link (store_id, category_id, priority)
SELECT id, category_id, 0
FROM store_store
WHERE category_id IS NOT NULL;
