我该如何设计此查询?

时间:2011-07-17 15:24:40

标签: mysql sql join foreign-keys

基本上;我在客户控制面板的公告页面上,我需要显示发布该公告的人的名字。我有他们的联系人ID。

$res = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 3;") or log_e();
/* Returns:
   Array {
     ['id'] = 1
     ['poster_id'] = 1
     ['when'] = CURRENT_TIMESTAMP
     ['title'] = "Example Announcement"
     ['message'] = "..."
   }
*/

UML设计文件的摘录如下: UML Design Document

我有“海报”,它与“用户”中的“id”有关...“用户”中的“main_contact”与联系人中的“id”有关。因此,我知道我需要join users on users.id = poster和...... join contacts on contacts.id = users.main_contact?但是整个查询会是什么样的?

谢谢,第一个回答。我能够把你的例子形成一个查询来完成我需要做的事情。

SELECT announcements.*, contacts.name_first FROM announcements 
  LEFT JOIN users on users.id = announcements.poster
  LEFT JOIN contacts on contacts.id = users.main_contact
ORDER BY announcements.id DESC LIMIT 3;

1 个答案:

答案 0 :(得分:1)

大致是:

SELECT a.*, c.[name_first] 
FROM announcements a 
  LEFT JOIN users b on a.id = b.poster 
  LEFT JOIN contacts c on c.id = b.main_contact 
ORDER BY a.id DESC LIMIT 3;