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

How to select one attribute from 2 tables?

本文关键字:属性 一个 选择      更新时间:2023-09-26

朋友 我有两个表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);

您可以使用 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"

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

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