简体   繁体   English

如何将这两个查询合并为一个

[英]how to combine these two queries into one

I have three tables: posts , cat_collection , and cat_mapping 我有三个表: postscat_collectioncat_mapping
posts contains the fields you would expect to see in a table named posts id, type, title, body, author, email, date, ect.. posts包含您期望在名为posts id,类型,标题,正文,作者,电子邮件,日期等的表中看到的字段

cat_collection contains id, name, description cat_collection包含ID,名称,描述

cat_mapping contains *id, collection_id, post_id* cat_mapping包含* 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 我目前有两个查询,第一个从帖子中选择信息,第二个从cat_collectioncat_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. 将“ cat_collection”别名为cat会造成混淆-表是关于cat而不是cat的集合的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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