简体   繁体   中英

How can I combine four queries into one query?

Structure of my tables:

posts (id, name, user_id, about, time)    
comments (id, post_id, user_id, text, time)
users_votes (id, user, post_id, time)
users_favs ( id, user_id, post_id, time)

How can I combine these four queries (not with UNION ):

SELECT `id`, `name`, `user_id`, `time` FROM `posts` WHERE `user_id` = 1
SELECT `post_id`, `user_id`, `text`, `time` FROM `comments` WHERE `user_id` = 1
SELECT `user`, `post_id`, `time` FROM `users_votes` WHERE `user` = 1
SELECT `user_id`, `post_id`, `time` FROM `users_favs` WHERE `user_id` = 1

Should I use JOIN s?

What would the SQL query for this be?

You don't want to join these together.

The kind of JOIN you'd use to retrieve this would end up doing a cross-product of all the rows it finds. This means that if you had 4 posts, 2 comments, 3 votes, and 6 favorites you'd get 4*2*3*6 rows in your results instead of 4+2+3+6 when doing separate queries.

The only time you'd want to JOIN is when the two things are intrinsically related. That is, you want to retrieve the posts associated with a favorite, a vote, or a comment.

Based on your example, there's no such commonality in these things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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