MYSQL Select 多对多

MYSQL Select many to many

我正在与两个 table 一起工作:评论、用户

评论table 有一个包含用户 ID 的收件人字段

现在我们必须将comment/recipient改为多对多的关系,因为多个用户可以收到相同的评论,所以我添加了linktable、comment_recipient

但是,现在我不确定在 select 发表评论

时如何 select 收件人列表

我不确定如何select 根据特定收件人发表评论

这是我现在拥有的:

$sql = "SELECT c.*, [RECIPIENTS]
FROM comment AS c
JOIN user AS u2 ON c.sender = u2.id
WHERE c.type<=?";
if(isset($args['location'])) $sql .= " AND u2.location=?";
if(isset($args['userId'])) {
  if(isset($args['given'])) {
    $sql .= " AND c.sender=?";
  }else {
    $sql .= " AND c.recipient=?"; //need to see if in recipient list now?
  }
}

编辑:

感谢 Barry 的回答,我现在得到了这个:

$sql = "SELECT c.*
FROM comment_recipient AS cr
JOIN comment AS c ON c.id=cr.comment_id
JOIN user AS u2 ON c.sender = u2.id
WHERE c.type<=?";
if(isset($args['location'])) $sql .= " AND u2.location=?";
if(isset($args['userId'])) {
  if(isset($args['given'])) {
    $sql .= " AND c.sender=?";
  }else {
    $sql .= " AND cr.user_id=?";
  }
}
$sql .= " GROUP BY c.id";
$sql .= " ORDER BY c.date DESC";
$sql .= " LIMIT ?";
$sql .= " OFFSET ?";

然后我将使用第二个查询 select 每个评论的收件人

假设您有以下 tables:

  • 用户(ID、姓名)

  • 评论(ID,姓名)

  • CommentRecipient ( User_ID, Comment_ID ) - 它们都是 上面 table 的外键。

是不是这么简单: 要在知道评论时获取收件人查询链接 table:

SELECT User_ID from CommentRecipient where Comment_ID= mycommentid;

反之亦然

SELECT Comment_ID from CommentRecipient where User_ID= myuserid;

抱歉,如果我误解了问题。