【问题标题】:SQL: FInding a Query to Filter Products through Selected Category IDsSQL:查找查询以通过选定的类别 ID 过滤产品
【发布时间】:2015-12-19 12:04:37
【问题描述】:



图片中显示了两个表格,即 ProductProductCategory。 现在的问题是,(假设)当从前端选择的类别(C_ID)是“3”、“5”、“4”。那么在 JOINProduct 表的帮助下,输出必须是“wer”。

当所选类别为“5”、“4”、“8”时,输出必须为“什么都没有”。你能帮我写一个 SQL 查询来做吗? 注意:选择类别后只需要显示常见产品。

【问题讨论】:

  • 您使用的是 MySQL 还是 MS SqlServer?所以你只想在匹配一个产品时输出产品?
  • 正如发布的那样,您的问题没有多大意义。这将是一个很好的起点。 spaghettidba.com/2015/04/24/…
  • 使用 MS SqlServer,是的 Nicky。
  • 假设:每次用户都必须选择准确的三个类别?
  • 不,它可以是 1 或 5。

标签: c# mysql .net sql-server inner-join


【解决方案1】:

这可能会有所帮助:

         declare var1 varchar(100)
      if exists (select 1 from productcategory where C_id in ('3','4','5')
         begin 
         set @var1= (select top 1 b.name 
         from productcategory a 
         join product b 
         on a.P_id=b.id) 
         end
       else set @var1='Nothing'

Join 操作会将名称存储在 var1 中,您可以编写一个返回 var1 的函数。

【讨论】:

  • 好吧,兄弟,再次阅读我的问题。如果 3、4、5 有共同产品,则显示产品名称。
  • @LoneRay 你从来没有在你的问题中写过这个。 selected from front end is "3", "5", "4". then the output has to be "wer" 。也许您应该再次阅读自己的问题? :)
  • 对不起,英语也有点弱;)
【解决方案2】:

试试

SELECT MAX(ISNULL(Name,'Nothing')) FROM
(SELECT MAX(Product.Name) AS Name
 FROM Product INNER JOIN ProductCategory ON ProductCategory.P_ID = Product.ID
 WHERE ProductCategory.C_ID IN (3,4,5)
 HAVING COUNT(*) = 1)Q1 

显然将(3,4,5) 替换为为给定设置传入的任何内容。

【讨论】:

    【解决方案3】:

    你需要使用类似的东西:

    if ((select count(distinct product.name) from...) > 1) select 'Nothing'
    else select distinct product.name from ...
    

    或使用类似的东西:

    select distinct @name = product.name from ...
    if (@@rowcount > 1) select 'Nothing'
    else select @name 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多