1

我有一个叫做画廊的东西,它把媒体组合在一起。该媒体可以是照片或视频。我将照片存储在一个表中,将视频存储在另一个表中,因此我使用 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_idand type

这是迄今为止我整理的最复杂的查询,我确信我缺少一些东西。如果画廊仅包含视频或仅包含照片,我希望结果能够反映这一点。

作为一个黑客,我可以在回显某些内容之前检查是否有一个ID当我对这些结果进行 foreach 时,但我知道我的查询可以得到改进。帮助?

4

1 回答 1

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;

此外,听起来你可能会从阅读我写的这篇关于 SQL 的文章中获得很多好处,以帮助你更好地理解这些概念。

于 2013-09-06T02:47:47.867 回答