简体   繁体   English

查询一个表,以从另一个表获取名称

[英]Query one table, to get name from another table

I have 3 tables in my database, Categories,Subcategories and Articles. 我的数据库中有3个表,类别,子类别和文章。 My Articles table contains columns caled CategoryID and SubcategoryID, which are foreign keys of the table Categories and Subcategories. “我的文章”表包含名为“类别ID”和“子类别ID”的列,它们是表“类别”和“子类别”的外键。

My question is, how can I get the name of the Category and Subcategory stored only as ID's in my Articles Table. 我的问题是,如何获取仅作为ID存储在我的文章表中的类别和子类别的名称。

I think I need a kind of subquery or join. 我想我需要一种子查询或联接。

Here is what I have: 这是我所拥有的:

SELECT ArticleTitle
      ,CategoryID
      ,SubcategoryID 
  FROM Articles 
 WHERE SubcategoryID = 
        (SELECT SubcategoryName 
           FROM Subcategories 
          WHERE SubcategoryName = 'info'
         )      

When I execute this code in mysql, there are no erros, but I receive 0 results. 当我在mysql中执行此代码时,没有错误,但是我收到0个结果。 All tables are containing some data. 所有表都包含一些数据。

change this: 改变这个:

where SubcategoryID = (select SubcategoryName from Subcategories 

to this 对此

where SubcategoryID in (select SubcategoryID from Subcategories 

the changes were 变化是

  1. the equal sign is now the word in . 现在等号这个词in
  2. the subquery is selecting SubcategoryID instead of SubCategoryName 子查询正在选择SubcategoryID而不是SubCategoryName

Using Joins : 使用联接:

SELECT a.ArticleTitle AS ArticleTitle, c.CategoryName AS CategoryName,s.SubcategoryName AS SubcategoryName 选择a.ArticleTitle AS ArticleTitle,c.CategoryName AS CategoryName,s.SubcategoryName AS SubcategoryName

FROM

Articles a JOIN Categories c on a.CategoryID=c.ID JOIN Subcategories s on a.SubcategoryID=s.ID 文章a.CategoryID = c.ID上的JOIN类别c在a.SubcategoryID = s.ID上的JOIN子类别s

WHERE s.SubcategoryName = 'info'; WHERE s.SubcategoryName ='info';

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

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