简体   繁体   English

PHP mysql查询计算左连接中的重复值

[英]PHP mysql query counting repeating values in left join

I have two tables - projects and sites.我有两张桌子 - 项目和网站。

I want to show a table with project number and site addresses, but where there's multiple sites per project show "Multiple Sites", and where there's no site assigned to a project show "No site".我想显示一个包含项目编号和站点地址的表格,但是每个项目有多个站点显示“多个站点”,并且没有分配给项目的站点显示“无站点”。

So I would like my table to look like this:所以我希望我的桌子看起来像这样:

Project Number项目编号 Site Address网站地址
job1工作1 123 Fake Street 123假街
job2工作2 5 sydney street 5 悉尼街
job3工作3 Multiple Sites多个站点
job4工作4 No site没有网站

But currently my table looks like this.但目前我的桌子看起来像这样。

Project Number项目编号 Site Address网站地址
job1工作1 123 Fake Street 123假街
job2工作2 5 sydney street 5 悉尼街
job3工作3 1 First Street 1 第一街
job3工作3 2 Second street 2 第二街
job4工作4 No site没有网站

with job3 repeating.与 job3 重复。 My code looks like this:我的代码如下所示:


<?php
    $query = mysqli_query($conn, 
        "SELECT projects.project_number,
            sites.address,
            sites.project_fk
            FROM projects
            LEFT JOIN sites
            ON projects.id = sites.project_fk");
?>

<div class="container">
    <table class="table">
         <thead>
            <tr>
            <th scope="col">Project Number</th>
            <th scope="col">Site</th>
            </tr>
        </thead>
        <tbody>
          <?php
            while ($row = mysqli_fetch_array($query)) {
                echo "<td>".$row["project_number"]."</td>";
                if ($row["address"] == null) {
                echo "<td>No Site</td>";
                } else {
                echo "<td>".$row[1]."</td>";
                }
                echo "</tr>";
                }
            ?>
        </tbody> 
    </table>
</div>

Is there a way to do this?有没有办法做到这一点? Do I have to create a new query which counts the number of 'sites' which are the same, and if so how do I do this?我是否必须创建一个新查询来计算相同的“站点”数量,如果是,我该怎么做?

Thanks!谢谢!

Use group by and case to determine if there are multiple, single or none addresses使用 group by 和 case 来确定是否有多个、单个或无地址

SELECT projects.project_number,
        CASE
        WHEN COUNT(*) > 1 then 'Multiple sites'
        WHEN COUNT(*) = 1 then sites.address
        WHEN COUNT(*) = 0 then 'No site'
        END as address
FROM projects
LEFT JOIN sites ON projects.id = sites.project_fk
GROUP BY projects.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM