【发布时间】:2017-06-23 11:46:42
【问题描述】:
我有一个不返回所需值的连接语句。
原因是第三个表 (cvi) 在许多情况下不会包含与第四个表 (cmi) 匹配的任何行。如果未连接任何值,则结果不会显示表 c 和 cv 中的所需值。
/* 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 位于表 cv 和 cmi 之间,因此这两个表中没有公共值。
+------------+
| c |
| |
| +-----|------+
| | | cv |
+------------+ |
| +------------+
| | | cvi | When this table is empty, the result is empty
+-------|----+ | I want it to still show result of c and cv
| +------------+
| | | cmi |
+------------+ |
| |
| |
+------------+
这里说明了为什么没有共享价值观。
因此,我正在寻找一种方法来创建一个仅在 cvi 包含值时才加入 cmi 的条件。否则只在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 |
+------+-----------+------------+
这是cv 和cmi 表中有数据时的结果。
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
)
)
【问题讨论】:
-
您能展示数据示例并解释您期望的结果集吗?目前你只有
inner join所以你不能得到任何结果(看看你的插图)。 -
当
c中有对应的行时,我希望表c中的每行至少有一个结果(此连接是图中未显示的连接)。所以c和cv之间存在内部连接。如果所有表中只有可用值,则此内部连接是正确的并产生正确的结果。但是如果第三个表cvi中没有值,那么到第四个表cmi的链接是“损坏的”,它会从c和cv表的内部连接中删除值。即使cvi和cmi表中没有要连接的值,这些也需要保留在结果中。
标签: php mysql codeigniter join