多表查询加入

时间:2011-10-07 20:13:51

标签: php mysql join

由于我是PHP的新手,我发现解决这个问题非常复杂。我有这个查询显示用户不应该做的结果。

问题是销售代理能够看到他无权查看的用户的投诉。这适用于客户的帐户表。

$priv = "dire problem" , 
$naone = "not serious" , 
$priv2 = "mild prblem" 
are sorting conditions. 
$aid is the agent viewing this page.  

Complaints is for complaints by the customers. 
Accounts table holds all the customer information. 
Agents table is for all the sales/customer reps. 

代码:

$sql = "SELECT complaints.complaint_id, accounts.full_name,
agents.agent_name, complaints.person_id, complaints.why_complaint, 
complaints.just_date, complaints.type, complaints.date_time_added FROM 
complaints LEFT JOIN accounts ON complaints.person_id = accounts.person_id 
LEFT JOIN agents on complaints.agent_whois = agents.agent_id WHERE 
(complaint_type = '$priv' OR complaint_type = '$naone' OR complaint_type = '$priv2') and  
 (complaints.added_by <> '$aid')"; 
 $result=mysql_query($sql);

 $query = mysql_query($sql) or die ("Error: ".mysql_error());

 if ($result == "")
 {
 echo "";
 }
 echo "";


 $rows = mysql_num_rows($result);

 if($rows == 0)
 {
 print("");

 }
 elseif($rows > 0)
 {
 while($row = mysql_fetch_array($query))
 {

  $complaintid = $row['complaint_id'];
  $agentwho = $row['person_id'];
  $agentname = $row['agent_name'];
 $reason = $row['why_complaint'];
 $datetimeadded = $row['just_date'];
  $docname = $row['full_name'];
  $type = $row['type'];


   print("");
   }

    }

1 个答案:

答案 0 :(得分:1)

这不是一个真正的答案,但无论如何我都会发布它,因为它是我能做的最好的。

好的,首先,你的缩进遍布各处。 ,为了任何需要阅读您的代码的人,请使用一致的indentation style。使用哪种风格并不重要 - 只需选择一种并始终如一地应用它。它使您的代码更容易阅读。

那就是说,让我们来看看你的查询。这是原始形式,只是为了更好的可读性而重新缩进:

SELECT
  complaints.complaint_id,
  accounts.full_name,
  agents.agent_name,
  complaints.person_id,
  complaints.why_complaint, 
  complaints.just_date,
  complaints.type,
  complaints.date_time_added
FROM
  complaints
  LEFT JOIN accounts ON complaints.person_id = accounts.person_id 
  LEFT JOIN agents ON complaints.agent_whois = agents.agent_id
WHERE
  ( complaint_type = '$priv'
    OR complaint_type = '$naone'
    OR complaint_type = '$priv2' )
  AND (complaints.added_by <> '$aid')

事实上,我们可以像这样更紧凑地重写WHERE子句:

WHERE
  complaint_type IN ('$priv', '$naone', '$priv2')
  AND complaints.added_by <> '$aid'

但所有这一切都表明,complain_type必须是三个值中的一个,并且代理'$aid'不得添加投诉。你说那个

  

“问题是销售代理能够看到他无权查看的用户的投诉。”

但是在查询中绝对没有关于任何类型授权的内容!由于我甚至无法从查询中猜出您的表可能包含哪种授权数据,或者您想要使用它做什么,我能给您的唯一建议是找出一些规则来告诉应该显示的记录从那些不应该和将它们添加到查询