多个SQL查询连接子查询

时间:2016-09-12 20:32:25

标签: sql join subquery

据我所知,sql查询无法动态添加和删除列。 每个站点都将拥有相同的额外数据。 所以我需要做的是从' z'中获取所有数据。并链接表中的某些字段。

表tt_transaction和表tt_extendeddatatype是独立的。 tt_extendeddatadetail有2个外键。 1)fk-> tt_transaction.id 2)fk - > tt_extendeddatatype

我需要使用扩展数据来提取每个事务。每个站点都具有相同的扩展数据名称。

我认为以下破解的代码演示了我想要做的比我能解释的要好得多。

SELECT z.*, aaa.name, aaa.value, bbb.name, bbb.value FROM tt_transaction
LEFT JOIN
(
    SELECT a.name, a.description, b.value, b.transaction_id AS text FROM tt_extendeddatatype AS a
    INNER JOIN tt_extendeddatadetail AS b ON a.id = b.type_id
    WHERE  a.name = 'Number'
) AS aaa 
ON aaa.transaction_id = z.id
LEFT JOIN
(
    SELECT a.name, a.description, b.value, b.transaction_id AS text FROM tt_extendeddatatype AS a
    INNER JOIN tt_extendeddatadetail AS b ON a.id = b.type_id
    WHERE  a.name = 'STRING'
) AS bbb
ON bbb.transaction_id = z.id

我当前的错误是列aaa.transaction_id不存在

1 个答案:

答案 0 :(得分:0)

<li>

您在子查询中将列SELECT z.*, aaa.name, aaa.value, bbb.name, bbb.value FROM tt_transaction LEFT JOIN ( SELECT a.name, a.description, b.value, b.transaction_id AS transaction_id FROM tt_extendeddatatype AS a INNER JOIN tt_extendeddatadetail AS b ON a.id = b.type_id WHERE a.name = 'Number' ) AS aaa ON aaa.transaction_id = z.id LEFT JOIN ( SELECT a.name, a.description, b.value, b.transaction_id AS text FROM tt_extendeddatatype AS a INNER JOIN tt_extendeddatadetail AS b ON a.id = b.type_id WHERE a.name = 'STRING' ) AS bbb ON bbb.transaction_id = z.id 命名为TEXT