帮助JOIN查询

时间:2010-06-19 12:02:30

标签: sql

我有以下3个表

table ads
...
categoryID
subcategoryID


table category
categoryID
description

table subcategory
subCategoryID
description

如何加入此3表以获取ADS和类别描述以及子类别描述中的所有字段...

(当我使用sql server时,我可以“设计”关系,但现在,我正在使用mysql,我没有图形环境来做它...而且我不好写sql)

提前谢谢

4 个答案:

答案 0 :(得分:2)

SELECT 
    ads.*,
    c.description as categoryDescription,
    sc.description as subcategoryDescription,
FROM
    ads 
    INNER JOIN category c ON c.categoryID = ads.categoryID
    INNER JOIN subcategory sc ON sc.subcategoryID = ads.subcategoryID

注意:最好使用显式列列表而不是'*'

答案 1 :(得分:1)

SELECT ads.categoryID,  
       ads.subcategoryID, 
       category.description AS category,  
       subcategory.description AS subcategory
FROM ads 
    JOIN category ON ads.categoryID = category.categoryID
    JOIN subcategory ON ads.subCategoryID = subcategory.subCategoryID

我原则上避免使用ads.*

答案 2 :(得分:1)

SELECT
  ads.*,
  category.description AS categorydescription,
  subcategory.description AS subcategorydescription
FROM ads
INNER JOIN category ON ads.categoryID = category.categoryID
LEFT JOIN subcategory ON ads.subcategoryID = subcategory.ID

我已将子类别保留为左联接,以防您的“广告”记录仅存在于顶级类别而不存在于子类别中。如果您的“广告”记录在子类别中始终 ,请将其切换为内部联接。

这也假设您的广告只出现在一个类别和子类别

答案 3 :(得分:0)

SELECT a.`categoryID`,a.`subcategoryID`,c.`description` AS catDesc,s.`description` AS subCatDesc FROM `ADS` a 
INNER JOIN `category` c ON a.`categoryID`=c.`categoryID` 
INNER JOIN `subcategory` s ON a.`subcategoryID`=s.`subCategoryID`

SQL应该这样做,你可以通过catDesc访问类别表描述,通过subCatDesc访问子类别描述,通过categoryID访问categoryID,通过subcategoryID访问子类别ID