多个mySQL加入PDO查询

时间:2014-04-18 10:46:22

标签: mysql pdo

我有一个关于复杂的mySQL查询的问题,该查询涉及用户表,帖子表和评论表以及评论的2个关系表。基本上我需要调用某个帖子的所有评论并检索发布评论的用户的名字。我的表结构如下:

users:
--Fields:
----id
----name
----email
----password

posts:
--Fields:
----id
----post_title
----post_category
----post_content
----image_url
----created_at

comments:
--Fields:
----id
----comment
----mood
----created_at

post_comments (which holds the relationship between the post and the comment):
--Fields:
----id
----post_id
----comment_id

user_comments (which holds the relationship between the user and the comment):
--Fields:
----id
----user_id
----comment_id

到目前为止,我已经编写了查询以按主题ID检索评论:

SELECT pc.id, c.id AS comment_id, c.comment, c.mood, p.id AS post_id 
FROM post_comments pc 
INNER JOIN posts p ON pc.post_id=p.id 
INNER JOIN comments c ON pc.comment_id=p.id 
WHERE pc.post_id=:post_id

这很有效,但我不知道如何通过user_comment关系表调用用户名。

1 个答案:

答案 0 :(得分:1)

我会这样做

SELECT
    users.name
FROM
    post_comments
JOIN
    comments
    ON comments.id = post_comments.comment_id
JOIN
    user_comments
    ON user_comments.comment_id = comments.id
JOIN
    users
    ON users.id = user_comments.user_id
WHERE
    post_comments.post_id = 1

除非您在查询中需要posts表格的字段,否则我会从post_comments开始(否则以posts开头)。

正如评论中所讨论的,1:n关系可以用一个表上的列来表示,以引用另一个表。

在你的情况下:

users:
--Fields:
----id
----name
----email
----password

posts:
--Fields:
----id
----post_title
----post_category
----post_content
----image_url
----created_at

comments:
--Fields:
----id
----post_id (which holds the relationship between the post and the comment)
----user_id (which holds the relationship between the user and the comment)
----comment
----mood
----created_at

因此,查询将更改为:

SELECT
    users.name
FROM
    comments
JOIN
    users
    ON users.id = comments.user_id
WHERE
    comments.post_id = 1

经验法则是:

  • 1:n关系(例如,书籍有很多页面,一页只属于一本书)

    - > 2个表(表pages包含引用book_id表的主键的books

  • n:m关系(例如,食谱中含有多种成分,一种成分可用于许多食谱中)

    - > 3个表格(表格recipes,表格ingredients,表格ingredients_recipesrecipe_idingredient_id