How do I query one table, but get related information from another table?
for example i have two tables:
posts {id,user_id,date}
design{user_id, bg_color}
and i have a post id of 18
for开发者_如何学JAVA example, i want to retrieve the design's table by the same user_id of that post(which is 18)
how can i query this?
sorry for this stupid, im confused ? :))
SELECT design.user_id, design.bg_color
FROM posts
JOIN design
ON posts.user_id = design.user_id
WHERE posts.id = 18
In other words, we first select from posts
where id
is 18;
then we join design
rows on which the user_id
equals the user_id
of the posts
row.
We retrieve the corresponding user_id
and bg_color
from the design
table.
Note that if there are multiple rows with the same design.user_id, you will get multiple rows back - example:
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'
query result:
posts.id | posts.user_id | design.user_id | design.bg_color
18 9 9 '#000000'
18 9 9 '#cafe00'
SELECT design.*
FROM design
JOIN posts on posts.user_id = design.user_id
where posts.ID = 18
You mean this?:
SELECT design.*
FROM design
JOIN posts ON design.user_id = posts.user_id
WHERE posts.id = ?givenid
Keep in mind that this could, based on the information you've given us, be a many-to-one relation. Are you looking for a single record or multiple records from the design
table?
SELECT `design`.* FROM `design`, `posts` WHERE `posts`.`user_id` = `design`.`user_id` AND `posts`.`id` = 18
select * from posts join
design on
posts.user_id=design.user_id
where posts.id=18
Your question is a little confusing, but I think this will do the trick:
SELECT * FROM `posts` LEFT JOIN `design` USING (`user_id`) WHERE `posts`.`id` = 18
精彩评论