如何在PHP中合并具有相同ID的数据?

时间:2015-11-24 14:01:03

标签: php mysql sql tsql

我的选择返回如下值: http://php.net/manual/en/mysqli.affected-rows.php

它可以将两条线合并为一条线?如果是这样,有可能在php或Tsql中? 就像是: enter image description here

这是我的选择:

$resultdelete = $conn->query($sqldelete);

3 个答案:

答案 0 :(得分:1)

改写,我想你说,当TRM_ID_TURMA相同时,选择一行,然后加入(用逗号' s)ALU_MATRICULA和NOMEALUNO的内容。

是吗?

如果是这样,我认为你应该在PHP中解决它,因为这比在SQL中要容易得多(无论你碰巧使用哪种方言对我来说都是个谜,我看到mysql,sql,oracle和tsql)。

假设您已运行查询,并将结果存储在关联结果集,数组中,然后尝试以下操作:

$RS = ......your query that results in an array.......
/* 
$RS looks like:
array(
 [0] => array("TRM_ID_TURMA"=>48, "TRM_HORA_INICIO" => "10:00:00 000000", ..etc..),
 [1] => array("TRM_ID_TURMA"=>49, "TRM_HORA_INICIO" => "10:00:00 000000", ..etc..)
 [2] => etc etc
)
*/

$tmp = array();
foreach ($RS as $one){
  // $tmp used TRM_ID_TURMA as key, and row as content
  if (isset($tmp[$one["TRM_ID_TURMA"]])){
    // TRM_ID_TURMA already used, add to the fields ALU_MATRICULA and NOMEALUNO.
    $tmp[$one["TRM_ID_TURMA"]]["ALU_MATRICULA"] .= ", " . $one["ALU_MATRICULA"];
    $tmp[$one["TRM_ID_TURMA"]]["NOMEALUNO"] .= ", " . $one["NOMEALUNO"];
  } else {
    $tmp[$one["TRM_ID_TURMA"]] = $one;
  }
}

您想要的结果现在是$ tmp(以TRM_ID_TURMA作为键)

答案 1 :(得分:0)

在mysql中,看一下GROUP_CONCAT函数。

SELECT TRM_ID_TURMA, GROUP_CONCAT(USU.USU_NOME NOMEALUNO)
FROM [MGB].[dbo].[TB_TURMA]
GROUP BY TRM_ID_TURMA

请注意group_concat_max_len,因为如果超过此长度,您的结果将会被截断。

答案 2 :(得分:0)

请阅读THIS ARTICLE 它展示了如何使用" FOR XML"来连接字段值。 此代码来自本文:

USE AdventureWorks2008R2
SELECT      CAT.Name AS [Category],
            STUFF((    SELECT ',' + SUB.Name AS [text()]
                        — Add a comma (,) before each value
                        FROM Production.ProductSubcategory SUB
                        WHERE
                        SUB.ProductCategoryID = CAT.ProductCategoryID
                        FOR XML PATH('') — Select it as XML
                        ), 1, 1, '' )
                        — This is done to remove the first character (,)
                        — from the result
            AS [Sub Categories]
FROM  Production.ProductCategory CAT