如何从相同的多个数据库结果中选择一个结果(How to select one result from same multiple database results)

我正在创建一个收件箱页面,我从收件箱数据库中回显出用户的行,但是如果你知道我的意思,用户会出现多次出现在数据库表中,这是我的意思的图像:

所以kanayo这个伟大的名字出现在桌子上的次数。 我希望名称只出现一次,以便在单击时显示消息正文。

这是我的代码:

$mymsg = mysql_query("SELECT msg_from, msg_to FROM message WHERE msg_from='$my_id' OR msg_to='$my_id' ORDER BY msg_id DESC LIMIT $start, $per_page"); while($run_msg = mysql_fetch_array($mymsg)){ $msg_from = $run_msg['msg_from']; $msg_to = $run_msg['msg_to']; if($msg_from == $my_id){ $users = $msg_to; } else { $users = $msg_from; } $firsts = getuser($users, 'first'); $nicks = getuser($users, 'nick'); $lasts = getuser($users, 'last'); echo "<div align='left'><a href='message.php?user=$users' style='text-decoration:none;><<b><font color='blue'>$firsts $nicks $lasts</font</b></a></div><br>"; }

我在我包含的外部文件中有我的函数和数据库连接。

这也是我的表的图像,我不知道它是否是收件箱的正确表格结构。

I am creating an inbox page where i echoed out the rows of the user from the inbox database but a user appears multiple times as appeared on the database table if you know what I mean, here is an image of what I mean:

So the name kanayo the great appears as much times it appeared in the table. I want the name to appear just once so that when clicked on it will display the message body.

Here is my code:

$mymsg = mysql_query("SELECT msg_from, msg_to FROM message WHERE msg_from='$my_id' OR msg_to='$my_id' ORDER BY msg_id DESC LIMIT $start, $per_page"); while($run_msg = mysql_fetch_array($mymsg)){ $msg_from = $run_msg['msg_from']; $msg_to = $run_msg['msg_to']; if($msg_from == $my_id){ $users = $msg_to; } else { $users = $msg_from; } $firsts = getuser($users, 'first'); $nicks = getuser($users, 'nick'); $lasts = getuser($users, 'last'); echo "<div align='left'><a href='message.php?user=$users' style='text-decoration:none;><<b><font color='blue'>$firsts $nicks $lasts</font</b></a></div><br>"; }

I have my functions and db connection in external files which I included.

This is an image also of my table, I don't know if its the right table structure for an inbox.

最满意答案

最好的方法是移动你的条件(检查是否等于my_id进入mysql查询,并让结果变量为“users”)。 然后和查询结束,你可以添加;

GROUP BY users

这将确保您只撤回不同的“用户”

您可以使用IF元素将条件合并到mysql中,即

SELECt IF(msg_from = '$my_id', msg_to, msg_from) AS users

Best way would be to move your condition (checking if equal to my_id into the mysql query, and let the resulting variable be "users"). Then and the end of the query, you can add;

GROUP BY users

Which will make sure you only pull back distinct "users"

You can incorporate a condition into mysql using the IF element, i.e.

SELECt IF(msg_from = '$my_id', msg_to, msg_from) AS users

更多推荐