To perform the query in a single query and fetch the data from the module_table for all module_ids, you can use the following modified code:\n\njavascript\nconst test_module_query = {\n text: 'SELECT t1.*, mht.module_id FROM public.tests AS t1 INNER JOIN modules_has_tests AS mht ON t1.uuid = mht.test_id',\n};\n\nconst getAlleyData = await client.query(test_module_query);\nconsole.log("getAlleyData",getAlleyData.rows);\n\nconst testModuleIds = getAlleyData.rows.map(row => row.module_id);\n\nasync function fetchDataForAllModules() {\n const moduleDataQuery = {\n text: 'SELECT * FROM modules WHERE uuid = ANY($1::uuid[])',\n values: [testModuleIds],\n };\n\n const moduleDataResult = await client.query(moduleDataQuery);\n console.log("moduleDataResult",moduleDataResult.rows);\n\n const combinedData = [];\n for (const row of getAlleyData.rows) {\n const moduleId = row.module_id;\n const moduleData = moduleDataResult.rows.find(data => data.uuid === moduleId);\n\n combinedData.push({\n test: row,\n module: moduleData,\n });\n }\n\n return combinedData;\n}\n\nconst allData = await fetchDataForAllModules();\n\n\nIn this modified code, the initial query test_module_query retrieves both the test data and the corresponding module_ids in a single query. Then, the fetchDataForAllModules function uses the retrieved module_ids to fetch the module data from the module_table using the ANY operator in the query. The module data is then combined with the test data to create the desired combinedData array.

Optimize PostgreSQL Queries: Combining Multiple Queries into One

原文地址: https://www.cveoy.top/t/topic/p2A8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录