PostgreSQL
 sql >> डेटाबेस >  >> RDS >> PostgreSQL

PostgreSQL तालिका में प्राथमिक कुंजी बदलें

मैंने कुछ समय बिताया है और अंत में एक कामकाजी समाधान के साथ आया हूं।

मैं इसे भविष्य के संदर्भ के लिए यहां प्रकाशित करूंगा।

समाधान

सबसे पहले, आपके पास तीन टेबल हैं (foo_table , bar_table , baz_table ) जो आपके users . की ओर इशारा कर रहे हैं विदेशी कुंजियों के माध्यम से तालिका (जिसे user_id कहा जाता है) सभी मामलों में)। आपको उन कॉलम में संग्रहीत आईडी को id . से बदलना होगा another_id . के लिए . यहां बताया गया है कि आप इसे कैसे कर सकते हैं:

-- We are dropping the foreign key constraint on dependant table (in other case it will prevent us from updating the values)
ALTER TABLE foo_table DROP CONSTRAINT fk_e52ffdeea76ed395;

-- Then, we're swapping values in foreign key column from id to another_id
UPDATE foo_table T SET user_id = (SELECT another_id FROM users WHERE id = T.user_id);

-- And finally we're creating new foreign key constraint pointing to the another_id instead of id
ALTER TABLE foo_table ADD CONSTRAINT fk_e52ffdeea76ed395 FOREIGN KEY (user_id) REFERENCES users (another_id) ON DELETE CASCADE;

आपको प्रत्येक आश्रित तालिका के लिए उपरोक्त प्रश्नों को दोहराना होगा।

उसके बाद, सभी आश्रित तालिकाएं आपके नए another_id . की ओर इशारा करेंगी कॉलम।

अंत में हमें केवल प्राथमिक कुंजी को बदलने की आवश्यकता होगी:

-- 1. Dropping the original primary key
ALTER TABLE users DROP CONSTRAINT users_pkey

-- 2. Renaming existing index for another_id (optional)
ALTER INDEX uniq_1483a5e93414710b RENAME TO users_pkey

-- 3. Creating new primary key using existing index for another_id
ALTER TABLE users ADD PRIMARY KEY USING INDEX users_pkey

-- 4. Creating index for old id column (optional)
CREATE UNIQUE INDEX users_id ON users (id)

-- 5. You can drop the original sequence generator if you won't need it
DROP SEQUENCE users_id_seq

आप मूल id भी छोड़ सकते हैं यदि आप चाहें तो कॉलम।

मुझे आशा है कि यह किसी की मदद करेगा।




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. JDBC के माध्यम से PostgreSQL तालिका में daterange फ़ील्ड मान डालें

  2. Postgres में फ़ंक्शन ओवरलोडिंग को अक्षम करने का कोई तरीका है

  3. प्रत्येक स्कीमा django के साथ सुपरयुसर को स्वत:बनाएँ

  4. 'संघ' पर या उसके पास PostgreSQL सिंटैक्स त्रुटि

  5. एकाधिक स्तंभों में अद्वितीय मान बाधा