如何从2个表中选择一个属性?

时间:2014-04-02 09:04:40

标签: javascript sql

朋友我有两张桌子BrandCategories和BrandOffers。两个表都有一个列名" brandId"。现在我正在使用我在下面写过的两个独立查询来选择brandId。

Select brandId from BrandCategories where categoryId   = "selectedCategory" AND isDeleted=0
Select brandId from BrandOffers     where discountType = "selectedDiscountType"

我想在一个查询中选择brandId,其中包含两个表的结果?我怎么能这样做?

我尝试过以下书面查询

SELECT brandId FROM BRANDCATEGORIES INNER JOIN BRANDOFFERS on BRANDCATEGORIES.brandId = BRANDOFFERS.brandId where BRANDCATEGORIES.categoryId='+brandCategorySelected+' AND BRANDOFFERS.discountTypeArabic="'+$('#DiscountDrop').val()+'" AND BRANDCATEGORIES.isDeleted=0

请告诉我是错还是对吗?

在我的程序中,我写了如下:

    db.transaction(function(tx) {tx.executeSql('(SELECT brandId FROM BRANDCATEGORIES INNER JOIN BRANDOFFERS on BRANDCATEGORIES.brandId = BRANDOFFERS.brandId where BRANDCATEGORIES.categoryId='+brandCategorySelected+' AND BRANDOFFERS.discountTypeArabic="'+$('#DiscountDrop').val()+'" AND BRANDCATEGORIES.isDeleted=0)', [], testing, errorCB);}, errorCB);

2 个答案:

答案 0 :(得分:1)

你可以使用UNION。

Select brandId from BrandCategories where categoryId   = "selectedCategory"
UNION
Select brandId from BrandOffers     where discountType = "selectedDiscountType"

UNION是编写UNION DISTINCT的较短方法。 如果您还想获得两个表中的键,请使用UNION ALL

Select brandId from BrandCategories where categoryId   = "selectedCategory"
UNION ALL
Select brandId from BrandOffers     where discountType = "selectedDiscountType"

答案 1 :(得分:0)

如果您希望获得两个查询的不同值,请使用union union all如果想要获得两个查询的所有结果(这可能会导致重复):

Select brandId from BrandCategories where categoryId   = "selectedCategory"
union all
Select brandId from BrandOffers     where discountType = "selectedDiscountType"