doupian9490 2014-01-01 23:36
浏览 63
已采纳

如果在连接查询中没有B值,则获取具有A值的项目(重复项)

sorry if the title is vague .

i have these table :

image : id , title 
image_tags : image_id , tag 
image_categories  : image_id , category_id 

in the image page , i want to get similar images by tag , from the same category but i want to exclude some categories

so here is my query :(lets say my curernt image has category : 1 , tag : a,b and i want to ignore category : 6,7)

SELECT image_tags.image_id 
FROM   image_tags 
       JOIN image_categories 
         ON image_categories.image_id = image_tags.image_id 
WHERE  image_tags.tag IN ( 'a', 'b' ) && image_categories.category_id IN ( 1 ) 
       && 
              image_categories.category_id NOT IN ( 6, 7 ) 

that works but if i have

       image_tags ( image_id , tag ) : 
        `128` , `a`
    --------------------------------------------
        image_categories (image_id , category_id ) :
        `128` , `1`
        `128` , `6`

i'll get the image with id = 128 on account of the first row in the image_categories

i have to somehow check and ignor image 128 becuz if second row ( category_i : 6 )

hopefully my question is not very confusing

  • 写回答

1条回答 默认 最新

  • dongzan2740 2014-01-01 23:41
    关注

    Group on image_id and test the categories using a suitable aggregate function within the HAVING clause:

    SELECT   image_id
    FROM     image_tags JOIN image_categories USING (image_id)
    WHERE    image_tags.tag IN ('a','b')
    GROUP BY image_id
    HAVING   SUM(image_categories.category_id IN (1))
         AND NOT SUM(image_categories.category_id IN (6,7))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c