如何从多个表中选择值

时间:2012-11-03 09:55:36

标签: mysql sql

我试图获取所有用户输入相同的行,但我试图从多个表中获取值。

$query=
"SELECT * 
 FROM (client OR agent OR admin) 
 WHERE (first='".$mysqli->real_escape_string($_SESSION['first'])."' 
    AND last='".$mysqli->real_escape_string($_SESSION['last'])."' 
    AND password='".$mysqli->real_escape_string($_SESSION['pass'])."')";

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

<?php
$first = $mysqli->real_escape_string($_SESSION['first']);
$last = $mysqli->real_escape_string($_SESSION['last']);
$password = $mysqli->real_escape_string($_SESSION['pass']);

$query=
"SELECT *
 FROM client, agent, admin
 WHERE (client.first = '$fist' AND client.last = '$last' AND client.password = '$password')
 OR (agent.first = '$fist' AND agent.last = '$last' AND agent.password = '$password')
 OR (admin.first = '$fist' AND admin.last = '$last' AND admin.password = '$password')";

这是获取数据的方式,但现在您必须检查存在哪些表数据,为此您可以使用mysqli_fetch_field

顺便说一下,考虑重新组织数据库表的选项,因为客户端,代理和管理员可以存储在一个表users中,其中列typerole代表客户端,代理或管理员。此方法称为database normalization。之后,您的查询和数据获取将更加简单和快速。