如何查询一个表,但从另一个表中获取相关信息?

时间:2010-12-30 14:10:00

标签: mysql sql

例如我有两个表:

posts {id,user_id,date}
design{user_id, bg_color}

我有post id of 18例如,我想通过该帖子的相同user_id检索设计的表格(18)

我该如何查询?

对不起这个傻瓜,我很困惑? :))

6 个答案:

答案 0 :(得分:4)

SELECT design.user_id, design.bg_color
FROM posts
JOIN design
  ON posts.user_id = design.user_id
WHERE posts.id = 18

换句话说,我们首先从posts中选择id为18; 然后我们加入design行,user_id等于user_id行的posts。 我们从user_id表中检索相应的bg_colordesign

请注意,如果有多个行具有相同的design.user_id,则会返回多行 - 例如:

posts.id  | posts.user_id
 1           5
 3           2
 18          9


design.user_id | design.bg_color
 2                '#aaffcc'
 5                'red'
 5                'blue'
 9                '#000000'
 9                '#cafe00'

查询结果:

posts.id | posts.user_id | design.user_id | design.bg_color
 18         9               9                '#000000'
 18         9               9                '#cafe00'

答案 1 :(得分:2)

SELECT design.*
  FROM design
  JOIN posts on posts.user_id = design.user_id
 where posts.ID = 18

答案 2 :(得分:1)

你是说这个?:

SELECT design.*
FROM design
    JOIN posts ON design.user_id = posts.user_id
WHERE posts.id = ?givenid

请记住,根据您提供给我们的信息,这可能是多对一的关系。您是在寻找design表中的单条记录还是多条记录?

答案 3 :(得分:1)

SELECT `design`.* FROM `design`, `posts` WHERE `posts`.`user_id` = `design`.`user_id` AND `posts`.`id` = 18

答案 4 :(得分:0)

    select * from posts join 
design on 
posts.user_id=design.user_id 
where posts.id=18

答案 5 :(得分:0)

你的问题有点令人困惑,但我认为这会解决问题:

SELECT * FROM `posts` LEFT JOIN `design` USING (`user_id`) WHERE `posts`.`id` = 18