简体   繁体   English

有人可以帮我进行mysql查询吗?

[英]Can someone help me with a mysql query please?

I have a question about building a mysql query from multiple tables. 我有一个关于从多个表构建mysql查询的问题。 The tables are following: 下表如下:

comments: comment_id, entry_id, user_id, comment, time..
users: user_id, user_name..
profile_photos: photo_id, user_id, photo_name

I want to get all comments from comments table for a specific entry_id , and for all of those users(who wrote comment), i want to get the photo_id(from profile_photos table, and user_name from users table). 我想从注释表中获取特定entry_id所有comments ,对于所有这些用户(写了注释),我想从photo_id(从profile_photos表中获取,并且user_name从用户表中)。

For example 2 users user_id "1" and "2" wrote comment on "entry_id" "1". 例如,2个用户user_id“ 1”和“ 2”在“ entry_id”“ 1”上写了评论。 I want to get the comments data from comments table for those two users, as well as their user_name and photo_id. 我要从这两个用户的评论表中获取评论数据,以及他们的user_name和photo_id。

If anyone can help me with the query, i will be really thankful. 如果有人可以帮助我进行查询,我将非常感激。

SELECT
      c.comment_id,
      c.user_id,
      c.comment,
      c.time,
      u.user_name,
      p.photo_name
   from
      comments c
         join users u
            on c.user_id = u.user_id
         left join profile_photos p
            on u.user_id = p.user_id
  where
     c.entry_id = WhateverNumberYouWant

Add on whatever other columns from respective aliased tables ("c" = comment, "u" = users, "p" = photos) 在相应别名表上添加其他任何列(“ c” =注释,“ u” =用户,“ p” =照片)

The LEFT join is just in case there is no photo yet for a given user... it won't exclude any entries by such user. 如果某个给定用户还没有照片,则使用LEFT加入...不会排除该用户的任何条目。

SELECT comment, user_name, photo_name
FROM comments
JOIN users ON (comments.user_id = users.user_id)
JOIN profile_photos ON (users.user_id = profile_photos.user_id)
WHERE entry_id = {entry_id}

Try the following where entry_id is xxx, I included the user_name too 尝试以下方法,其中entry_id为xxx,我也包含了user_name

select comments.comment,profile_photos.photo_id,users.user_name
from comments,users,profile_photos
where
  comments.entry_id = xxx and
  users.user_id = comments.user_id and
  users.user_id = profile_photos.user_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM