duanli9930 2011-03-13 03:41
浏览 18
已采纳

MySQL加入和排除?

I have two tables, table A one with two columns: IP and ID, and table B with columns: ID and extra information. I want to extract the rows in table B for IPs that are not in table A. So if I have a rows in table A with

id = 1
ip = 000.000.00
id = 2
ip = 111.111.11

and I have rows in table B

id = 1
id = 2

then, given ip = 111.111.11, how can I return row 1 in table B?

  • 写回答

2条回答 默认 最新

  • dtvnnhh8992 2011-03-13 03:46
    关注

    The simplest and most easy-to-read way to spell what you're describing is:

    SELECT * FROM `B` WHERE `ID` NOT IN (SELECT `ID` FROM `A`)
    

    You should be aware, though, that using a subquery for something like this has historically been slower than doing the same thing with a self-join, because it is easier to optimise the latter, which might look like this:

    SELECT
       `B`.*
    FROM
       `B`
    LEFT JOIN
       `A` ON `A`.`ID` = `B`.`ID`
    WHERE
       `A`.`ID` IS NULL
    

    However, technology is improving all the time, and the extent to which this is true (or even whether this is true) depends on the database software you're using.

    You should test both approaches then settle on the best balance of readability and performance for your use case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?