如何对子查询进行这些查询?

时间:2013-03-01 11:14:48

标签: sql subquery inner-query

如何将其转换为单个查询。我已经制定了以下查询:

$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;
                }

2 个答案:

答案 0 :(得分: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

我已加入所有表格,以便返回所有必填字段

答案 1 :(得分: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和message表的结构是什么,你为什么要加入它们?

编辑:那怎么样?

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个查询更有效)