简体   繁体   中英

Counting rows in left joined table

I have 2 tables: users and log. Currently my query looks like that.

        $stmt = $this->db->prepare("SELECT u.id, u.email, u.salt, u.pass, u.approved, u.ban, u2.status  FROM `users` AS u LEFT OUTER JOIN `log` AS u2 ON u2.user_id = u.id WHERE u.email = ?") or die($this->db->error);
        $stmt->bind_param("s", $_POST['email']) or die($stmt->error);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows == 0) {
            die($this->ajax->respond(7));
        }
        $data = array();
        $stmt->bind_result($data['id'], $data['email'], $data['salt'], $data['pass'], $data['approved'], $data['ban'], $data['status']) or die($stmt->error);
        $stmt->fetch() or die($stmt->error);
        $stmt->close() or die($stmt->error);

Status column of log table - is indicates if user already signed in or not. What I want to do is to check if email exists in users table and to count rows of log table where status=1 . Is that possible with one and only query?

In other words:

Here is log table

在此处输入图片说明

Take a look at rows where status = 1. This indicates that user 1 currently signed in. To prevent second signin from different browser I want to at first check for email in users table (basic signin procedure) and at that moment check if user not signed in (by counting rows where status = 1 in log table)

Just change the query to this -

SELECT u.id, u.email, u.salt, u.pass, u.approved, 
u.ban, SUM(u2.status) AS status FROM `users` AS u 
LEFT JOIN `log` AS u2 ON u2.user_id = u.id 
WHERE u.email = ?
GROUP BY u.id

There are a number of other ways to do this as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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