php – MySQL选择JOIN 3 Tables

前端之家收集整理的这篇文章主要介绍了php – MySQL选择JOIN 3 Tables前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个基本表:
tblUsers:

    usrID     usrFirst     usrLast
      1        John          Smith
      2        Bill          Jones
      3        Jane          Johnson

pm_data:

id     date_sent              title          sender_id  thread_id         content
2   2009-07-29 18:46:13     Subject 1           1         111        Message 2!
3   2009-07-29 18:47:21     Another Subject     1         222        Message 3!

pm_info:

id  thread_id   receiver_id  is_read
1     111           2            0
2     111           3            0
3     222           2            0
4     222           3            0

基本上,我想要做的是创建一个收件箱.

因此,如果usrID 2(Bill Jones)打开他的收件箱,他会看到他2个未读(因此是’is_read’列)消息(线程#111和#222).

基本上,我需要知道如何将我的SELECT语句设置为JOIN所有三个表(pm_data和pm_info之间的关系带来了消息信息,而tblUsers和pm_data之间的关系带来了发送者的’显示名称’),在顶部显示最新的(按时间戳?)线程.

因此,我们会看到这样的事情:

<?PHP  $usrID = 2;  ?>

<table id="messages">
  <tr id="id-2">
  <td>
   <span>
     From: John Smith
    </span>
    <span>2009-07-29 18:47:21</span>
  </td>
 <td>
 <div>Another subject</div>
 </td></tr>
<tr id="id-1">
 <td>
   <span>
     From: John Smith
   </span>
   <span>2009-07-29 18:46:13</span>
</td>
 <td>
   <div>Subject 1</div>
 </td></tr>
 </table>

希望这是有道理的!谢谢你的帮助!

编辑:这是我的最终答案:

我接受了lc的建议,并根据id建立了两个表之间的关系(在pm_info中添加了一个名为’message_id’的列).

然后,稍微调整一下MysqL语句来得出这个:

SELECT pm_info.is_read,sender.usrFirst as sender_name,pm_data.date_sent,pm_data.title,pm_data.thread_id
FROM pm_info
INNER JOIN pm_data ON pm_info.message_id = pm_data.id
INNER JOIN tblUsers AS sender ON pm_data.sender_id = sender.usrID
WHERE pm_data.date_sent IN(SELECT MAX(date_sent) FROM pm_data WHERE pm_info.message_id = pm_data.id GROUP BY thread_id) AND pm_info.receiver_id = '$usrID' ORDER BY date_sent DESC

这似乎对我有用(到目前为止).

你需要两个连接.像下面这样的东西应该让你开始(虽然我不是100%理解pm_data和pm_info之间的关系):
SELECT pm_info.is_read,sender.usrFirst + ' ' + sender.usrLast as sender_name,pm_data.thread_id
FROM pm_info
INNER JOIN pm_data ON pm_info.thread_id = pm_data.thread_id
INNER JOIN tblUsers AS sender ON pm_data.sender_id = tblUsers.usrID
WHERE pm_info.receiver_id = @USER_ID /*in this case,2*/
ORDER BY pm_data.date_sent DESC

我假设pm_data和pm_info之间的关系是线程ID.如果不是,您应该可以根据需要调整上述内容.我也按照这里发送的日期排序,但它不会保持线程在一起.我不确定你是否愿意将它们放在一起或不同意你的问题.

如果要将线程保持在一起,则需要更复杂的查询

SELECT pm_info.is_read,pm_data.thread_id
FROM pm_info
INNER JOIN pm_data ON pm_info.thread_id = pm_data.thread_id
INNER JOIN tblUsers AS sender ON pm_data.sender_id = tblUsers.usrID
INNER JOIN (SELECT thread_id,MAX(date_sent) AS max_date
            FROM pm_data
            GROUP BY thread_id) AS most_recent_date 
           ON pm_data.thread_id = most_recent_date.thread_id
WHERE pm_info.receiver_id = @USER_ID /*in this case,2*/
ORDER BY most_recent_date.max_date DESC,pm_data.thread_id,pm_data.date_sent DESC

查询使用子选择查找每个线程的最新修改日期,然后按此排序.

原文链接:/php/135211.html

猜你在找的PHP相关文章