在 MS SQL Server 中,此查询正常运行:
SELECT column1
, (SELECT RelatedColumn1 FROM tbl_related WHERE record_id=a1.record_id) AS pseudocolumn1
, (SELECT RelatedColumn2 FROM tbl_related WHERE record_id=a1.record_id) AS pseudocolumn2
, (SELECT RelatedColumn3 FROM tbl_related WHERE record_id=a1.record_id) AS pseudocolumn3
, (SELECT RelatedColumn4 FROM tbl_related WHERE record_id=a1.record_id) AS pseudocolumn4
... [20 or more subqueries here] ...
FROM tbl_primary a1
然而,在 mySQL 中,这运行得非常慢——并且随着您添加更多子查询,性能会继续下降。我确信它与幕后操作的顺序有关,但我的问题是如何优化这个查询?如何将第二个表中的所有值转换为结果集中的列?希望这不必通过多个 JOIN 语句来完成(因为我不太了解 JOINS)...?