2个表上的UNION每次返回一个几乎为空的结果

时间:2013-09-06 02:39:26

标签: php mysql left-join union

我有一些名为Galleries的媒体将媒体分组在一起。该媒体可以是照片或视频。我将照片存储在一个表格中,将视频存储在另一个表格中,因此我使用UNION查询来查找属于图库的照片和视频。

我的问题似乎是我的结果包含其中一个表的空对象(没有ID) - 重新定义,如果该表中没有结果,它将始终为正在查询的其中一个表返回无用的结果。

首先,查询:

SELECT * from (
    SELECT g.id AS gallery_id,  'photo' AS type, p.id AS id, p.filename, p.caption, null AS title, null AS service, null AS embed, null AS width, null AS height, p.display_order FROM galleries g 
        LEFT OUTER JOIN photos AS p ON p.gallery_id = g.id
        WHERE g.id = {$this->id}
    UNION
    SELECT g.id AS gallery_id, 'video' AS type, v.id AS id, null AS filename, null AS caption, v.title, v.service, v.embed, v.width, v.height, v.display_order FROM galleries g 
        LEFT OUTER JOIN videos AS v ON v.gallery_id = g.id 
        WHERE g.id = {$this->id}
) AS u ORDER BY display_order;

我正在添加type列,以便我可以确定我得到的结果类型。我已经取消了表格之间不常见的结果。

就像我说的那样,它有效,但并不像预期的那样。如果我有一个只包含照片的图库,我仍会得到(几乎)空的视频结果。一个示例结果:

[] => Galleries Object
    (
        [id] => 
        [name] => 
        [slug] => 
        [gallery_id] => 32
        [type] => video
        [filename] => 
        [caption] => 
        [title] => 
        [service] => 
        [embed] => 
        [width] => 
        [height] => 
        [display_order] => 
    )

[39] => Galleries Object
    (
        [id] => 39
        [name] => 
        [slug] => 
        [gallery_id] => 32
        [type] => photo
        [filename] => 39-studio-blue-pacific.jpg
        [caption] => 
        [title] => 
        [service] => 
        [embed] => 
        [width] => 
        [height] => 
        [display_order] => 1
    )

标有[type]=>video的第一个结果为空,我称之为,因为它没有视频ID,标题,嵌入代码等...它只包含gallery_idtype

这是迄今为止我汇总的最复杂的查询,我确信有些东西是我遗漏的。如果图库仅包含视频或仅包含照片,我希望结果能够反映出来。

要成为一个黑客,我可以在回复某些内容之前检查是否有ID,但我知道我的查询可以改进。救命?

1 个答案:

答案 0 :(得分:2)

您获得这些结果的原因是因为您在表上使用外部联接。试试这个:

SELECT * from (
    SELECT g.id AS gallery_id,  'photo' AS type, p.id AS id, p.filename, p.caption, null AS title, null AS service, null AS embed, null AS width, null AS height, p.display_order FROM galleries g 
        JOIN photos AS p ON p.gallery_id = g.id
        WHERE g.id = {$this->id}
    UNION
    SELECT g.id AS gallery_id, 'video' AS type, v.id AS id, null AS filename, null AS caption, v.title, v.service, v.embed, v.width, v.height, v.display_order FROM galleries g 
        JOIN videos AS v ON v.gallery_id = g.id 
        WHERE g.id = {$this->id}
) AS u ORDER BY display_order;

此外,听起来您可以从阅读this article I wrote about SQL中获得很多好处,以帮助您更好地理解这些概念。