在3个具有不同列的不同表中搜索用户

时间:2014-04-18 06:11:23

标签: php mysql

我有这么久的时间。我有3个用户表。它们位于不同的表中,因为它们具有不同的列,具体取决于用户的类型。

现在登录该网站我正在尝试选择用户的电子邮件以及与他对应的所有其他值。基于其他用户的一些反馈,我写了这样的查询:

    $query = "SELECT id, position_id, first_name, last_name, email ";
    $query .= "FROM pims ";
    $query .= "WHERE email = '{$email}' ";
    $query .= "AND hashed_password = '{$hashed_password}' ";
    $query .= "AND com_code IS NULL ";
    $query .= "LIMIT 1 ";

    $query .= "UNION ALL SELECT id, district_id, position_id, first_name, last_name, email ";
    $query .= "FROM dms ";
    $query .= "WHERE email = '{$email}' ";
    $query .= "AND hashed_password = '{$hashed_password}' ";
    $query .= "AND com_code IS NULL ";
    $query .= "LIMIT 1 ";

    $query .= "UNION ALL SELECT * ";
    $query .= "FROM users ";
    $query .= "WHERE email = '{$email}' ";
    $query .= "AND hashed_password = '{$hashed_password}' ";
    $query .= "AND com_code IS NULL ";
    $query .= "LIMIT 1";

但是我收到“数据库查询失败”消息。当我只有一个SELECT语句时,查询工作正常,所以我知道这个查询不起作用。任何想法如何解决它?

2 个答案:

答案 0 :(得分:0)

首先,联合查询中的列数和类型必须相同。其次,我建议你为此做一个观点,然后使用视图以方便,因为我不认为这是你需要这样一个查询的唯一地点。

$query = "SELECT id, '' as district_id, position_id, first_name, last_name, email ";
$query .= "FROM pims ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";

$query .= "UNION ALL SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM dms ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";

$query .= "UNION ALL SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1";

答案 1 :(得分:0)

在所有查询中,联合all应具有相同的列数。

$query  = "SELECT id, 'garbage_data' AS district_id, position_id, first_name, last_name, email ";
$query .= "FROM pims ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";

$query .= "UNION ALL ";

$query .= "SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM dms ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";

$query .= "UNION ALL ";

$query .= "SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1";

如果您缺少列。您不能添加任何现有数据,如:

'garbage_data' AS district_id

这将显示一个字符串garbage_data,它可以使列数相同。

它可以是任何东西,它甚至可以是'' AS district_id