获取行并检查是否有相同的值

6rqinv9w  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(327)

我是一个非常新的编码和尝试学习php和mysql。我要做的是,在同一个表中对相同的customerid查询进行分组,同时生成一个echo。目前,我的代码回响所有分开的查询。我有一张像这样的table

ID      CustomerID     DATE        Company
1           1       2018-11-19        A
2           1       2018-11-19        A
3           2       2018-11-19        B
4           3       2018-11-19        C
5           4       2018-11-19        D
6           4       2018-11-19        D

我的代码

$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
        FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());

$result = $mysqli->query($query);

while($resultquery = $result->fetch_array())

{
$queryresult[] = $resultquery;

}
if (!empty($queryresult)) {

foreach($queryresult as $queryresults)
{

$id = $queryresults['id'];
$customerid = $queryresults['customerid'];  
$date = $queryresults['date'];
?>

然后我回音,结果是

Company Name: A
ID CustomerID DATE
1      1    2018-11-19

Company Name: A
ID CustomerID DATE
2      1    2018-11-19

Company Name: B
ID CustomerID DATE
3      2    2018-11-19

Company Name: C
ID CustomerID DATE
4      3    2018-11-19

<?php }} ?>

等。。
但是我想要的是比较customerid,如果有多个具有相同id的,则将它们作为一个组在表中进行回显。

Company Name: A
ID CustomerID DATE
1      1    2018-11-19
2      1    2018-11-19

Company Name: B
ID CustomerID DATE
3      2    2018-11-19

Company Name: C
ID CustomerID DATE
4      3    2018-11-19

我用group|concat进行了一个sql查询,并使用分隔符“|”)对结果进行了分组,它是有效的,但我认为实现这一点不是最好的,所以请帮助。谢谢您

xzlaal3s

xzlaal3s1#

将数据Map到以company为键的键值数组中(在查询中包括company:
$query=“选择 customers .id号, customers .客户ID, customers 。日期,公司起始日期 customers 其中月(日期)=月(当前日期()),年(日期)=年(当前日期())“;

$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
        FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());

然后使用键对项目进行分组以简化数据收集:

$result = $mysqli->query($query);
$queryresult = [];
while($resultquery = $result->fetch_array())

{
 $company = $resultquery['company'];
 if (array_key_exists($company,$queryresult){
   @$queryresult[$company] = [];
 }
 @$queryresult[$company][] = $resultquery;

}

然后您可以使用foreach显示信息:

foreach($queryresult as $company => $items){
   // header by company
   echo "Company Name: $company \n";
   echo "ID CustomerID DATE\n";
   foreach($items as $item){
     // items in company
     echo "{$item['id']} {$item['customerid']} {$item['date']}\n"; 
  }

}

相关问题