在 PostgreSQL 和 NodeJS 中擷取問題和投票
本文探討了使用 PostgreSQL 和 NodeJS 將問題及其相關投票作為單一 JSON 物件取得的有效方法。 我們將研究幾種方法,權衡它們的性能影響。
應用程式場景涉及使用者提問和投票(贊成或反對)。目標是檢索每個問題及其投票數組。
方法一:多次查詢(pg-promise)
此方法使用 pg-promise
執行多個查詢。 首先,它檢索所有問題。然後,對於每個問題,它都會獲得相應的投票。
function buildTree(t) { const v = q => t .any('SELECT id, value FROM votes WHERE question_id = ', q.id) .then((votes) => { q.votes = votes; return q; }); return t.map('SELECT * FROM questions', undefined, v).then((a) => t.batch(a)); } db.task(buildTree) .then((data) => { console.log(data); }) .catch((error) => { console.log(error); });
或者,用 ES7 async/await
:
await db.task(async (t) => { const questions = await t.any('SELECT * FROM questions'); for (const q of questions) { q.votes = await t.any('SELECT id, value FROM votes WHERE question_id = ', [q.id]); } return questions; });
方法二:單次查詢(PostgreSQL JSON 函數)
PostgreSQL 9.4 及更高版本提供了使用 JSON 函數的更有效率的單查詢解決方案:
SELECT json_build_object('id', q.id, 'content', q.content, 'votes', (SELECT json_agg(json_build_object('id', v.id, 'value', v.value)) FROM votes v WHERE q.id = v.question_id)) FROM questions q;
此查詢為每個問題建構一個 JSON 對象,包括投票的聚合數組。 與pg-promise
:
const query = `SELECT json_build_object('id', q.id, 'content', q.content, 'votes', (SELECT json_agg(json_build_object('id', v.id, 'value', v.value)) FROM votes v WHERE q.id = v.question_id)) json FROM questions q`; const data = await db.map(query, [], (a) => a.json);
效能比較
由於減少了資料庫往返次數,單一查詢方法(方法 2)明顯更快。 然而,方法1(多次查詢)提供了更好的可讀性和可維護性,特別是對於更複雜的場景。
為了在大型資料集上獲得最佳效能,請考慮連接子查詢等技術以最大限度地減少資料庫交互,如有關組合嵌套循環查詢的相關資源中所述。
以上是如何使用 NodeJS 在 PostgreSQL 中以單一 JSON 物件的形式高效檢索問題及其相關投票?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

todropaviewInmySQL,使用“ dropviewifexistsview_name;” andTomodifyAview,使用“ createOrreplaceViewViewViewview_nameAsSelect ...”。 whendroppingaview,asew dectivectenciesanduse和showcreateateviewViewview_name;“ tounderStanditSsstructure.whenModifying

mySqlViewScaneFectectialized unizedesignpatternslikeadapter,Decorator,Factory,andObserver.1)adapterPatternadaptSdataForomDifferentTablesIntoAunifiendView.2)decoratorPatternenhancateDataWithCalcalcualdCalcalculenfields.3)fieldfields.3)

查看InMysqlareBeneForsImplifyingComplexqueries,增強安全性,確保dataConsistency,andOptimizingPerformance.1)他們simimplifycomplexqueriesbleiesbyEncapsbyEnculatingThemintoreusableviews.2)viewsEnenenhancesecuritybyControllityByControllingDataAcces.3)

toCreateAsimpleViewInmySQL,USEthecReateaTeviewStatement.1)defitEtheetEtheTeViewWithCreatEaTeviewView_nameas.2)指定usethectstatementTorivedesireddata.3)usethectStatementTorivedesireddata.3)usetheviewlikeatlikeatlikeatlikeatlikeatlikeatable.views.viewssimplplifefifydataaccessandenenanceberity but consisterfort,butconserfort,consoncontorfinft

1)foralocaluser:createUser'localuser'@'@'localhost'Indidendify'securepassword'; 2)foraremoteuser:creationuser's creationuser'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Rocaluser'@'localhost'Indidendify'seceledify'Securepassword'; 2)

mysqlviewshavelimitations:1)他們不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinsOrsubqueries.2)他們canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

porthusermanagementinmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)複雜的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用