如何从连接表结果中分离值?

时间:2017-10-12 03:20:36

标签: php mysql codeigniter

我有一个简单的连接表,看起来像这样。

NO   CLASS     NAME    STATUS
 1      1A     JOHN         1
 2      1A     SARA         1
 3      1A     LYOD         1
 4      1B     JOHN         1
 5      1B     SHIN         1

我使用textbox来显示CLASSTEXTAREA以显示NAMECLASS 1A的输出应该是这样的:

Class : 1A
Name  : JOHN, SARA, LYOD

如何只使用联接表(不是多个查询)?

这就是我循环结果的方式:

$query  = $this->xxx->yyy($class_name); //JOINED RESULT

    $data = array(
        'titlepage'     => APP_TITLEPAGE,            
        'record'        => $query, //This is the result that is sent to the view
        'complete'      => 'true',
        'loadmethod'    => 'add',
        'contentpage'   => 'test_page/detail'   
    );

    $this->load->view('shared/master_app', $data);

2 个答案:

答案 0 :(得分:1)

如果要在一列中的同一个类中添加所有名称,则可以通过GROUP_CONCAT() mysql函数来实现。

使用GROUP_CONCAT调整查询。有关示例,请参阅下文

SELECT CLASS, GROUP_CONCAT(NAME) 
FROM  table_name 
GROUP BY CLASS;

它会像这样输出

1A JOHN,SARA,LYOD
2A JOHN,SHIN

您还可以使用GROUP_COCAT分隔符

在名称之间放置自定义分隔符
  SELECT CLASS, GROUP_CONCAT(NAME SEPARATOR ' -- ') 
    FROM  table_name 
    GROUP BY CLASS;

供参考MySql GROUP_CONCAT()

答案 1 :(得分:1)

所以你的查询数组是这样的:

$query = [
    ['NO' => 1, 'CLASS' => '1A', 'NAME' => 'JOHN', 'STATUS' => '1'],
    ['NO' => 2, 'CLASS' => '1A', 'NAME' => 'SARA', 'STATUS' => '1'],
    ['NO' => 3, 'CLASS' => '1A', 'NAME' => 'LYOD', 'STATUS' => '1'],
    ['NO' => 4, 'CLASS' => '1B', 'NAME' => 'JOHN', 'STATUS' => '1'],
];

您可以制作一个排列或分组的功能 让它命名为groupResults($ query)

function groupResults($query) {
    $result = [];
    foreach($query as $queryItem) {
        $result[$queryItem['CLASS']][] = $queryItem['NAME'];
    }
    return $result;
}

现在结果如下:

$result = [
    '1A' => ['JOHN', 'SARA', 'LYOD'],
    '1B' => ['JOHN']
]

这是我得到的快照:

enter image description here

现在你可以像这样使用它

$query  = $this->xxx->yyy($class_name); //JOINED RESULT
$data = array(
    'titlepage'     => APP_TITLEPAGE,            
    'record'        => groupResults($query), //This is the result that is sent to the view
    'complete'      => 'true',
    'loadmethod'    => 'add',
    'contentpage'   => 'test_page/detail'   
);

$this->load->view('shared/master_app', $data);

现在在视图中你可以在这个数组上循环:

foreach($record as $class => $names) {
    echo "<input type='text' value='" . $class . "'>";
    echo "<textarea>" . implode(', ', $names) . "</textarea>";
}