NULL上的第三次连接不返回值(Codeigniter)

时间:2017-06-23 11:46:43

标签: php mysql codeigniter join

我有一个不返回所需值的连接语句。

原因是第三个表(cvi)在许多情况下不包含与第四个表(cmi)匹配的任何行。如果未加入任何值,则结果不会显示表ccv中的所需值。

    /* Tables */
    $this->db->from($this->table_c.' c');
    $this->db->join($this->table_cv.' cv', 'cv.content_id = c.id', 'inner');
    $this->db->join($this->table_cvi.' cvi', 'cvi.version_id = cv.id AND cvi.meta_key = "M"');
    $this->db->join($this->table_cmi.' cmi', 'cmi.id = cvi.meta_value');

我已尝试过外连接,但由于表cvi位于表cvcmi之间,因此两个表中没有共同的值。

+------------+
|        c   |
|            |
|      +-----|------+
|      |     |  cv  |
+------------+      | 
       |       +------------+
       |       |    |  cvi  | When this table is empty, the result is empty
       +-------|----+       | I want it to still show result of c and cv
               |      +------------+
               |      |     |  cmi |
               +------------+      |
                      |            |
                      |            |
                      +------------+

以下是没有共享值的原因说明。 因此,我正在寻找一种方法,只有在cmi包含值时才会加入cvi。否则,只在cvi上进行外部联接,不要包含表cmi

您能提供一些想法或解决方案吗?

修改 为清晰起见,以下是表格:

/* Table c */
+------+--------+
| id   | title  |
+------+--------+

/* Table cv */
+------+----------+
| id   | version  |
+------+----------+

/* Table cvi */
+------+------------+-----------+------------+
| id   | version_id | meta_key  | meta_value |
+------+------------+-----------+------------+
/* when meta_key is 'M' then the meta_value will contain the cmi.id which is used for the join (regard it as meta_id) */
/* When this table is empty there won't be data in `cmi` either. When it's empty the join removes the data result that should be present from table `c`. */

/* Table cmi */
+------+-----------+------------+
| id   | item_key  | item_value |
+------+-----------+------------+

如果表cvcmi中有数据,则会产生以下结果。

Array (
        [0] => stdClass Object
            (
                [id] => 5 /* This is c.id */
                [title] => Content title
                [version_id] => 8 /* This is cv.id */
                [version] => 0
                [meta_key] => M
                [meta_value] => 23 /* (This is the id of the item below, cmi.id) */
                [item_key] => KEY1
                [item_value] => Value
            )
)

1 个答案:

答案 0 :(得分:0)

在我看来,你必须采取left joins

/* Tables */
$this->db->from($this->table_c.' c');
$this->db->join($this->table_cv.' cv', 'cv.content_id = c.id', 'inner');
$this->db->join($this->table_cvi.' cvi', 'cvi.version_id = cv.id AND cvi.meta_key = "M"', 'left');
$this->db->join($this->table_cmi.' cmi', 'cmi.id = cvi.meta_value', 'left');

如果cvi和cmi的连接条件没有产生任何结果,那么你将获得空列。

在评论后进行修改:也许EXISTS有帮助:

$this->db->where("EXISTS(SELECT * FROM cmi)");

Codeigniter subquery exists