假设我有一个对PostgreSQL
数据库进行的SQL查询。如您所见,我在重复相同的子查询只是为了获得另一列。我坚信这是无效的。您认为执行sql查询的最佳方法是什么?
SELECT
TABLE_A.COLUMN_1,
TABLE_A.COLUMN_2,
(
SELECT
TABLE_B.COLUMN_A,
FROM
TABLE_B
WHERE
TABLE_B.COLUMN_Z ILIKE CONCAT('%', TABLE_A.COLUMN_2, '%')
) AS COLUMN_3,
(
SELECT
TABLE_B.COLUMN_B,
FROM
TABLE_B
WHERE
TABLE_B.COLUMN_Z ILIKE CONCAT('%', TABLE_A.COLUMN_2, '%')
) AS COLUMN_4,
FROM
TABLE_A
答案 0 :(得分:1)
使用加入
SELECT
TABLE_A.COLUMN_1,
TABLE_A.COLUMN_2, TABLE_B.COLUMN_A AS COLUMN_3, ABLE_B.COLUMN_B AS COLUMN_4
FROM
TABLE_A
JOIN
TABLE_B ON TABLE_B.COLUMN_Z LIKE CONCAT('%', TABLE_A.COLUMN_2, '%')
答案 1 :(得分:1)
使用横向连接:
SELECT a.COLUMN_1, a.COLUMN_2, b.*
FROM TABLE_A a LEFT JOIN LATERAL
(SELECT b.COLUMN_A, b.COLUMN_B
FROM TABLE_B b
WHERE b.COLUMN_Z ILIKE CONCAT('%', a.COLUMN_2, '%')
) b
ON 1=1;