左连接有多个表和条件

时间:2013-10-29 22:01:54

标签: mysql sql left-join

我想在另一个表中的值之后对当前表的引用进行排序。我的查询如下:

SELECT o._id,
       o.titel,
       o.beschreibung
FROM   `objekt` AS o,
       `objekt_einzel` AS oe,
       `objekt_einzel_immobilie` AS oei,
       `objekt_art` AS oa,
       `verortung` AS v
       #here
       ,`person` AS p,
       `person_bauträger` AS pb
       #end
WHERE  o._id = oe.objekt_id
       AND oe._id = oei.objekt_einzel_id
       AND oa._id = o.objekt_art_id
       AND o.ort_id = v._id
       #here
       AND oe.bauträger_id = pb._id
       AND pb.person_id = p._id
       #end
       AND ( oei.justimmo_objekt_id = "0"
              OR oei.justimmo_objekt_id IS NULL
              OR oei.justimmo_objekt_id = "" )
#here
ORDER  BY p.firmenbezeichnung ASC

查询工作正常,但只显示oe.bauträger_id设置的值。我还想要null值。所以我需要一个左连接。我尝试了不同的东西,但我只收到unknown column这样的消息,或者我得到的结果太多了。

我试图将其简化为:

SELECT o._id,
       o.titel,
       o.beschreibung
FROM   `objekt` AS o,
       `objekt_einzel` AS oe,
        (SELECT oe.bauträger_id
        FROM objekt o, objekt_einzel oe, objekt_einzel_immobilie oei
        WHERE o._id = oe.objekt_id AND oe._id = oei.objekt_einzel_id) AS menge1
LEFT JOIN
        (SELECT pb._id AS bauträger_id
        FROM person p, person_bauträger pb
        WHERE p._id = pb.person_id) AS menge2
ON menge1.bauträger_id = menge2.bauträger_id
WHERE o._id = oe.objekt_id AND oe.bauträger_id = menge1.bauträger_id

但是我得到的结果太大了。我不知道如何更好地解释这一点。数据集太大,无法创建示例。我希望你明白我的意思。

1 个答案:

答案 0 :(得分:1)

SELECT o._id,
       o.titel,
       o.beschreibung
FROM   `objekt` AS o
       JOIN `objekt_einzel` AS oe ON o._id = oe.objekt_id
       JOIN `objekt_einzel_immobilie` AS oei ON oe._id = oei.objekt_einzel_id
       JOIN `objekt_art` AS oa ON o.objekt_art_id = oa._id
       JOIN `verortung` AS v ON o.ort_id = v._id
       LEFT JOIN `person_bauträger` AS pb ON oe.bauträger_id = pb._id
       LEFT JOIN `person` AS p ON pb.person_id = p._id
WHERE  oei.justimmo_objekt_id = "0"
       OR oei.justimmo_objekt_id IS NULL
       OR oei.justimmo_objekt_id = ""
ORDER  BY p.firmenbezeichnung ASC

第二次尝试应该有效,因为它只是使用JOIN语法和LEFT JOIN重写的原始代码。