2013-03-01 67 views
0

如何將其製作爲單個查詢。我制定了以下查詢:如何使這些查詢進行子查詢?

$msgs=mysql_query("select m.subject, m.msg from message as m, message_users as mu where m.id=mu.msg_id and mu.user_id=$u_id order by dateof_msg desc"); 
while($row1=mysql_fetch_array($msgs)) 
{ 
     $total_msg = $row1['msg']; 
     $own_id = mysql_query("select owner_id from message where msg='$total_msg' "); 
     while($o_id=mysql_fetch_array($own_id)) 
     { 
      $owners_id = $o_id['owner_id']; 
      $uname = mysql_query("select name from users where id='$owners_id'"); 

      while($username=mysql_fetch_array($uname)) 
      { 
       $sen_name = $username['name']; 
       echo $sen_name."&nbsp;&nbsp;".$owners_id."&nbsp;&nbsp;&nbsp;&nbsp;".$total_msg."<br />"; 
      } 
     } 
} 

由於查詢的運行時間確實很慢。

我現在編輯的這樣的代碼,但它說mysql_fetch_array()節選參數1是資源布爾給出...

$userlist = mysql_query("select m.subject, m.msg, m.owner_id, u.name, u.id, mu.msg_id, mu.user_id from message as m, message_users as mu, users as u 
            m inner join u on (m.owner_id = u.id) 
            m inner join mu on(m.id=mu.msg_id) and 
            where mu.user_id='$u_id' order by dateof_msg desc") or mysql_error(); 
       while($row=mysql_fetch_array($userlist)) 
       { 
        $sendername = $row['name']; 
        echo $sendername; 
       } 
+0

這是因爲該查詢不正確。把這個:'$ userlist = mysql_query(「...」)或死(mysql_error());'你會看到錯誤。 – RainHeart257 2013-03-01 13:21:12

回答

0

試試此問題:

select m.subject, m.msg, m.owner_id, users.name 
from message as m, message_users as mu 
    inner join users on (message.owner_id = users.id) 
where m.id=mu.msg_id and mu.user_id=$u_id order by dateof_msg desc 

如果你向我解釋你想做什麼,我可以改進答案:message_users和消息表的結構是什麼,你爲什麼要加入他們?

編輯:這是怎麼回事?

select m.id, m.subject, m.msg, owner.id, 
    owner.name, receivers.id, receivers.name 
from message as m 
    inner join message_users as mu on (m.id = mu.msg_id) 
    inner join users as owner on (m.owner_id = owner.id) 
    inner join users as receivers on (m.user_id = receivers.id) 
where receivers.user_id=$u_id 
order by dateof_msg desc 

的問題是,你會得到一個排的每個消息和每個接收器,但用PHP,你可以組的信息(比一回路3次的查詢更有效)

+0

開發消息通信系統消息表具有發送者的信息和message_users表具有誰是消息的接收者。 – AndRaGhu 2013-03-01 11:31:59

+0

而在此代碼中,您試圖獲取所有消息及其所有者並將其列入列表中,是不是?在這種情況下,你是否真的需要從message_users獲取數據? – RainHeart257 2013-03-01 11:39:22

+0

雅我需要從message_users表中得到接收者ID .. – AndRaGhu 2013-03-01 11:41:35

0

嘗試此查詢

select m.subject, m.msg, m.owner_id, u.name 
from message as m, message_users as mu, users as u 
where m.id=mu.msg_id and mu.user_id=<userId> and msg=<MESSAGE> and u.id = mu.userId 
order by dateof_msg desc 

我已經參加了所有所有必要的字段返回