我正在使用两个表:comment,user
评论表的收件人字段包含用户ID
现在我们必须将评论/收件人更改为多人关系,因为多个用户可以收到相同的评论,所以我添加了一个链接表,comment_recipient
但是,现在我不确定在选择评论时如何选择收件人列表
和
我不确定如何根据特定收件人选择评论
这就是我现在所拥有的:
$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 ?";
然后,我将使用第二个查询为每个评论选择收件人
答案 0 :(得分:1)
假设您有以下表格:
用户(ID,姓名)
评论(ID,姓名)
CommentRecipient(User_ID,Comment_ID) - 这两者都是 上表中的外键。
不是那么简单: 当您知道Comment查询链接表时获取收件人:
SELECT User_ID from CommentRecipient where Comment_ID= mycommentid;
反之亦然
SELECT Comment_ID from CommentRecipient where User_ID= myuserid;
很抱歉,如果我误解了这个问题。