【问题标题】:MySQLi SELECT rows from TableA where 0 rows in TableBMySQLi SELECT rows from Table where 0 rows in Table
【发布时间】:2015-11-07 09:51:51
【问题描述】:

表:实例

instanceID

表格:对象

objectID
instanceID

我如何从实例中获取所有行,其中 instanceID 在对象中有 0 行。

谢谢。

【问题讨论】:

    标签: php select mysqli


    【解决方案1】:

    效率不高,但您可以像这样简单地使用内部查询:

    select * from instance where instanceID not in (select instanceID from Objects)
    

    或者使用应该比内部查询更快的连接

    SELECT I.*
    FROM instance I LEFT JOIN Objects O ON I.instanceID = O.instanceID
    WHERE O.instanceID IS NULL
    

    【讨论】:

    • 我想知道在这种情况下where not exists (correlated subquery) 查询是否会更快。 @user1512064:在objects 中,给定的instanceID 是否有0 条或1 条记录,或者给定的instanceID 是否有n>1 条记录?
    • @VolkerK:你可以离开加入,我只是懒得考虑了:)
    • 我认为使用 LEFT JOIN/IS NULL 的第二种解决方案要好得多。这就是必须在没有子查询/存在的情况下完成的方式......我仍然更喜欢这种语法(我太老了,不适合那个exists shi....;-))
    • 除错之外,第二个语句完美运行。非常感谢=)
    【解决方案2】:

    select * from instances where (select count(instanceID) from objects) = 0;

    这是你所期待的吗?

    【讨论】:

    • 测试时,预期 1 时返回 0 行。无论如何,谢谢。
    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 2011-04-06
    • 2022-12-01
    • 1970-01-01
    • 2022-12-02
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多