du5114 2014-09-19 00:52
浏览 35
已采纳

从PHP MySQL的SELECT语句中获取重复值

My database has two tables: ips, oips

ips.public field contains values: 1, 2, 3, 4, 5, 6, 7, 8

oips.public field contains values: 1, 3, 7

I want to select all values in ips.public that do not appear in oips.public

I'm using the following MySQL query within PHP:

SELECT * FROM ips, oips WHERE ips_ips.public != oips.public

This is returning the following:

1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8

As you can see, the values that exist in both tables are only shown twice, whilst everything else is displayed three times (presumably due to this iterating on both tables).

Could anybody please shed some light on how to have this code so that it'd only return the values that are not in both tables (aka: 2, 4, 5, 6, 8)

Thanks!

  • 写回答

2条回答 默认 最新

  • dthp96899 2014-09-19 00:54
    关注

    There are several ways to do this.

    I prefer to use NOT EXISTS:

    SELECT *
    FROM ips i
    WHERE NOT EXISTS (
        SELECT 1
        FROM oips o
        WHERE i.ipublic = o.opublic)
    

    Here's NOT IN:

    SELECT *
    FROM ips
    WHERE ipublic NOT IN (SELECT opublic FROM oips)
    

    And here's LEFT JOIN/NULL:

    SELECT i.*
    FROM ips i
        LEFT JOIN opublic o ON  i.ipublic = o.opublic
    WHERE o.opublic IS NULL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看