如何连接多个查询

时间:2019-05-26 12:02:52

标签: php mysql sql

我用数据库中的数据创建了该表。 表格:https://imgur.com/06xnebJ

我需要将月份为May的所有行都放在1行中 像这样:

2019年5月| | 3 | 3 | 2 | 等

我的数据库如下:

https://imgur.com/nmwco9y

https://imgur.com/QbdGlzo

到目前为止,我已经获得了这段代码

$tipsportsql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '0' AND komentator1 = '$firstname $lastname' OR projekt = '0' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

$slaviasql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '1' AND komentator1 = '$firstname $lastname' OR projekt = '1' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

$betsql = mysqli_query($conn, "SELECT DATE_FORMAT(datum, '%b %Y') AS 'Monthyear', count(projekt) AS 'project' FROM zapasy WHERE projekt = '2' AND komentator1 = '$firstname $lastname' OR projekt = '2' AND komentator2 = '$firstname $lastname' GROUP BY Monthyear");

还有这个

<tbody>
        <?php while ($tip = mysqli_fetch_assoc($tipsportsql)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>

            </td>
            <td>

            </td>
            <td>
                <?=$tip['project']?>
            </td>
        </tr>

        <?php } while ($tip = mysqli_fetch_assoc($slaviasql)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>

            </td>
            <td>

            </td>
            <td>

            </td>
            <td>
                <?=$tip['project']?>
            </td>
        </tr>
        <?php }while ($tip = mysqli_fetch_assoc($betsql)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>

            </td>
            <td>
            <?=$tip['project']?>
            </td>
            <td>

            </td>
            <td>

            </td>
        </tr>
        <?php }?>
    </tbody>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我相信您想要这样的查询:

SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear, 
       SUM(projekt = 0) AS project_1,
       SUM(projekt = 1) AS project_2,
       SUM(projekt = 2) AS project_3
FROM zapasy
WHERE CONCAT(?, ?) IN (komentator1, komentator2)
GROUP BY Monthyear;

特别注意参数占位符。您需要学习如何使用参数,这样您的查询才不会遭受意外的语法错误和SQL注入攻击。