【问题标题】:How to join two tables in a query where the name of the table to be joined is a value in the first table如何在查询中连接两个表,其中要连接的表的名称是第一个表中的值
【发布时间】:2020-09-08 08:48:52
【问题描述】:

我有两个查询将 4 个表连接在一起。第四个表是从第一个表中读取的值。到目前为止,我一直在将该值读入一个变量,然后在第二个查询中使用这些变量,但我想知道是否可以将其合并到一个查询中。

这是我的查询($node_type_name 是从调用函数传入的):

$this->read_db->select('id, head_node_id, data_table_name');
    $this->read_db->from('node_type');
    $this->read_db->where('name', $node_type_name);
    $Q = $this->read_db->get();
    $table_name = $Q->row_array()['data_table_name'];
    $field_name = $table_name . '.node_id';
    $this->read_db->select('node.id, node.name, node.is_head_node, node.node_type_id, node_link.parent_node_id, ' . $table_name . '.id, ' . $table_name . '.node_id');
    $this->read_db->from('node');
    $this->read_db->join('node_link', 'node_link.child_node_id = node.id');
    $this->read_db->join($table_name, $field_name . ' = node.id');
    $M = $this->read_db->get();

该函数是一个通用函数,因此有人可以将locations 发送到$node_type_nameorganizations,查询将与与这些名称关联的表连接。目前只有两种“类型”,但我们将来可能会添加更多,因此函数需要是泛型的。

【问题讨论】:

  • 对我来说,这听起来像是数据库设计中的一个巨大错误。
  • @CBroe,你能解释一下吗?
  • 我猜你的表必须有非常相似的结构,因为你已经证明了什么是有意义的。但如果它们如此相似,那么这些数据很可能一开始就不应该分布在多个这样的表中。

标签: php mysql codeigniter


【解决方案1】:

最后,我创建了一个单独的函数,用于获取对象中的第一个查询,然后将其传递给第二个函数。

【讨论】:

    猜你喜欢
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多