如何将table1和table2相加(简单总和)

时间:2018-04-19 20:54:23

标签: php

我如何总结Table1和Table2

如果table1有多个条目状态为“0”而table2也有多个条目状态为“0”,则将Table1 + Table2加起来。

实施例

表1有3个状态为“0”的信号,而表2有2个状态为“0”的信号,则总和为2 像第一个表= 1和第二个表= 1

如果table1有条目而table2没有条目则sum为1 如果两者都没有条目,则sum为0

我尝试了这个if语句:

codecs.open(filename, encoding='utf8')

这是在计算通知。 状态1是重新通知,状态0不是重新通知。

我没有完成我的陈述,因为我知道这是错误的做法。

1 个答案:

答案 0 :(得分:1)

您可以使用以下SQL:

SELECT SUM(x.cnt)
FROM (
    SELECT IF(COUNT(*) > 0, 1, 0) AS cnt FROM contact WHERE status = 0
    UNION ALL
    SELECT IF(COUNT(*) > 0, 1, 0) FROM orrdr WHERE status = 0
)x

所以你可以使用以下PHP代码:

require_once('../../function.php');

try {
    $database = new Connection();
    $db = $database->openConnection();
    $status = 0;

    $sql = "SELECT SUM(x.cnt) FROM (SELECT IF(COUNT(*) > 0, 1, 0) AS cnt FROM contact WHERE status = :status UNION ALL SELECT IF(COUNT(*) > 0, 1, 0) FROM orrdr WHERE status = :status)x";
    $qry = $db->prepare($sql);
    $qry -> bindParam(':status', $status, PDO::PARAM_INT);
    $qry -> execute();
    $count = $qry->fetchColumn();
} catch (PDOException $e) {
    echo "There is some problem in connection: " . $e->getMessage();
}

echo $count;

如果您需要知道两个查询的总和,可以使用以下内容:

require_once('../../function.php');

try {
    $database = new Connection();
    $db = $database->openConnection();
    $status = 0;

    $sql = "SELECT (SELECT COUNT(*) FROM contact WHERE status = :status) AS cnt_contact, (SELECT COUNT(*) FROM orrdr WHERE status = :status) AS cnt_orrdr";
    $qry = $db->prepare($sql);
    $qry -> bindParam(':status', $status, PDO::PARAM_INT);
    $qry -> execute();
    $count_contact = $qry->fetchColumn(0);
    $count_orrdr = $qry->fetchColumn(1);
} catch (PDOException $e) {
    echo "There is some problem in connection: " . $e->getMessage();
}

if ($cnt_contact >= 1 && $cnt_orrdr >= 1) {
    echo "2"; //both available.
} elseif($cnt_contact >= 1 && $cnt_orrdr == 0) {
    echo "1"; //only contact available.
} elseif ($cnt_orrdr >= 1 && $cnt_contact == 0) {
    echo "1"; //only orrdr available.
} elseif ($cnt_orrdr == 0 && $cnt_contact == 0) (
    echo "0"; //nothing available.
}

//simpler solution instead of "if" above:
//echo (($cnt_contact > 0 ? 1 : 0) + ($cnt_orrdr > 0 ? 1 : 0));