【问题标题】:Combining results of Mysql Join结合Mysql Join的结果
【发布时间】:2016-10-07 10:14:39
【问题描述】:

Mysql 连接有问题。我有两张桌子,一张center_contacts 和一张center_contacts_notescenter_contacts_notes 通过两个表中的 contact_id 链接。

center_contacts_notes 内部,每个contact_id 可以有多行,我想获取所有这些并将它们放入结果的子数组中。

例如,我的center_contacts_notes 表如下所示:

contact_id   |   note
------------------------
1                test
2                hello
3                sup
1                moo

这是我试图获取数据的地方:

$this->db->select('center_contacts.id, FirstName, LastName, center_contacts_notes.note');
$this->db->from('center_contacts');
$this->db->join('center_contacts_notes', 'center_contacts_notes.contact_id = center_contacts.id');

请注意,我使用的是 Codeigniter 3。

这是我从中得到的:

Array
(
    [id] => 1
    [FirstName] => Bob
    [LastName] => Smith
    [note] => test
)
Array
(
    [id] => 1
    [FirstName] => Bob
    [LastName] => Smith
    [note] => moo
)

这是我的结果中的两个不同数组。这对我来说是不切实际的,因为我需要一个包含两个音符的数组。像这样的:

Array
(
    [id] => 1
    [FirstName] => Bob
    [LastName] => Smith
    [note] => Array(test, moo)
)

这可能吗?如果可以,我将如何实现?谢谢。

【问题讨论】:

  • 你试过GROUP_CONCAT()

标签: php mysql codeigniter join


【解决方案1】:

我不知道您是否可以像您提到的那样获得二维数组,但是有一种解决方法可以获得类似的结果。这可能对您有帮助。

您需要做的是使用Group Bygroup_concat()Group bycontact_id 的表并在center_contacts_notes.note 上应用group_concat()

您的查询应如下所示。

$this->db->select('center_contacts.id, FirstName, LastName, GROUP_CONCAT(center_contacts_notes.note)');
$this->db->from('center_contacts');
$this->db->join('center_contacts_notes', 'center_contacts_notes.contact_id = center_contacts.id');
$this->db->group_by('center_contacts.id');

默认情况下,group_concat 将通过, 连接列。您可以通过以下方式更改它。

GROUP_CONCAT(center_contacts_notes.note SEPARATOR 'YOUR_SEPARATOR_STRING')

这将返回如下结果:

Array
(
    [id] => 1
    [FirstName] => Bob
    [LastName] => Smith
    [note] => test[YOUR_SEPARATOR_STRING] moo
)

您可以使用PHP explode通过提供分隔符值将音符字符串转换为数组。

【讨论】:

  • Group_concat 似乎奏效了。它不是一个数组,但我仍然可以按预期解析它。谢谢。
猜你喜欢
  • 2013-10-07
  • 2015-08-15
  • 2014-11-09
  • 1970-01-01
  • 2017-09-27
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多