例如我有两个表:
posts {id,user_id,date}
design{user_id, bg_color}
我有post id of 18
例如,我想通过该帖子的相同user_id检索设计的表格(18)
我该如何查询?
对不起这个傻瓜,我很困惑? :))答案 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_color
和design
。
请注意,如果有多个行具有相同的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