从多个表中选择相同的值

时间:2014-04-07 19:58:47

标签: php mysql

我有3个表:user,physician,care_provider,它们都有用户名和电子邮件字段。

我需要确保为3种用户类型中的任何一种创建的用户名和电子邮件在所有3个表中都是唯一的。

有没有办法连接或联合表来检查每个表中的相同数据?

显然我可以做3次选择,但当然我更喜欢用一个查询检查用户名。

现在我只是像这样检查所有3个:

$count = 0;
$user = $this->db->query("
    SELECT COUNT(user_id) AS total 
    FROM " . DB_PREFIX . "user 
    WHERE username = '" . $this->db->escape($username) . "'
");
if ($user->row['total']):
    $count += $user->row['total'];
endif;
... (for each table) ...

return $count;

2 个答案:

答案 0 :(得分:0)

SELECT COUNT(*) AS total FROM table1, table2, table3 
WHERE table1.username = input
OR table2.username = input
OR table3.username = input

或者你可以做这样的问题。 mySQL select count, multiple tables

答案 1 :(得分:0)

以下是最终工作的内容:

$query = $this->db->query("
    SELECT SUM(total) AS total 
    FROM(
        SELECT COUNT(*) AS total 
            FROM " . DB_PREFIX . "user 
            WHERE username = '" . $this->db->escape($username) . "' 
            UNION ALL
        SELECT COUNT(*) AS total 
            FROM " . DB_PREFIX . "care_provider 
            WHERE username = '" . $this->db->escape($username) . "' 
            UNION ALL
        SELECT COUNT(*) AS total 
            FROM " . DB_PREFIX . "physician 
            WHERE username = '" . $this->db->escape($username) . "'
    ) AS t 
");

return $query->row['total'];