在MYSQL

时间:2015-07-13 09:40:16

标签: php mysql sql database codeigniter

Video
-------
id
source_low
source_med
source_high

Source
--------
id
duration
thumbnail

视频项目最多可包含1个源(源低,源med,源高)。

这个想法与youtube相同,这意味着视频记录可以包含多种质量。因此,当我返回持续时间/缩略图时,我想检查哪个源存在并返回其中一个。

例如,如果视频包含source_low或source_med,则表示存在持续时间& source_low和source_med的缩略图,然后我只需要返回其中一个。

Codeigniter语法:

  $this->db->select('v.*, sl.duration, sm.duration as duration_m, sh.duration as duration_h, sl.thumbnail, sm.thumbnail as thumbnail_m, sh.thumbnail as thumbnail_h');
        $this->db->from('video as v');
        $this->db->join('source as sl', 'v.source_low = sl.video_id', 'left');
        $this->db->join('source as sm', 'v.source_med = sm.video_id', 'left');
        $this->db->join('source as sh', 'v.source_high = sh.video_id', 'left');
        $this->db->group_by('v.id');

SQL(缩略图与获取的方式相同):

SELECT v.*, sl.duration, sm.duration as duration_sm, sh.duration as duration_sh
    FROM video as v
    LEFT JOIN source as sl ON (v.source_low = sl.video_id)
    LEFT JOIN source as sm ON (v.source_med = sm.video_id)
    LEFT JOIN source as sh ON (v.source_high = sh.video_id)
    GROUP BY v.id;

现在我可以返回所有结果,包括空值,但是如何只返回一个持续时间和一个缩略图?

感谢您的帮助

更新:

只是更新查询但似乎codeigniter在处理它时有一些错误, 任何的想法?感谢

我的代码:

$this->db->select('v.*, COALESCE(b.duration, bt.duration, bc.duration) AS duration, COALESCE(b.thumbnail, bt.thumbnail, bc.thumbnail) AS thumbnail');

在SQL中:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS duration, COALESCE(b.thumbnail, `bt`.`thumbnail`, `bc`.`thumbnail)` AS thumbn' at line 1

SELECT `v`.*, `t`.`name`, `t`.`name_tw`, `t`.`name_cn`, COALESCE(b.duration, `bt`.`duration`, `bc`.`duration)` AS duration, COALESCE(b.thumbnail, `bt`.`thumbnail`, `bc`.`thumbnail)` AS thumbnail FROM (`video` as v) JOIN `teacher` as t ON `v`.`teacher_id` = `t`.`id` LEFT JOIN `brightcove` as b ON `v`.`video` = `b`.`video_id` LEFT JOIN `brightcove` as bt ON `v`.`video_tw` = `bt`.`video_id` LEFT JOIN `brightcove` as bc ON `v`.`video_cn` = `bc`.`video_id` WHERE `v`.`is_delete` = 0 AND `v`.`type` = 0 GROUP BY `v`.`id` ORDER BY `v`.`start_date` desc

1 个答案:

答案 0 :(得分:6)

您可以使用COALESCE()函数返回第一个非空值。有关详细信息,请参阅MySQL manual。 E.g:

SELECT v.*, COALESCE(sl.duration, sm.duration, sh.duration) AS duration
    FROM video as v
    LEFT JOIN source as sl ON (v.source_low = sl.video_id)
    LEFT JOIN source as sm ON (v.source_med = sm.video_id)
    LEFT JOIN source as sh ON (v.source_high = sh.video_id)
    GROUP BY v.id;