简体   繁体   中英

how to combine these two queries into one

I have three tables: posts , cat_collection , and cat_mapping
posts contains the fields you would expect to see in a table named posts id, type, title, body, author, email, date, ect..

cat_collection contains id, name, description

cat_mapping contains *id, collection_id, post_id*

I currently have two queries, the first one selects the information from posts , the second retrieves the associated categories from cat_collection and cat_mapping

first

SELECT post.id, post.type, post.title, post.body, post.date, post.author, post.email
FROM posts AS post
WHERE post.id = 1

second

SELECT cat.name
FROM cat_collection AS cat
LEFT JOIN cat_mapping AS map ON map.collection_id = cat.id
WHERE map.post_id = 1

Is there a way to return all of the post information, as well as the list of associated categories with a single query?

If I understand your data model, you just need another left join. You may want to re-order the joins to make sure that your query is efficient and returns the right data.

SELECT
  posts.id,
  posts.type,
  posts.title,
  posts.body,
  posts.date,
  posts.author,
  posts.email,
  cat.name
FROM
  posts
LEFT JOIN 
    cat_mapping AS map ON map.post_id = posts.id
LEFT JOIN 
    cat_collection AS collection ON map.collection_id = collection.id
WHERE
  posts.id = 1

Please think carefully about your aliases. Aliasing "posts" to "post" is silly. Aliasing "cat_collection" to cat is confusing - the table is about collections of cats, not cats.

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