SELECT WHERE<>给出无限循环

时间:2017-12-14 10:56:52

标签: php mysql sql

我需要选择那些在另一个表中不存在的记录。

公司

    JSONObject postData = new JSONObject();
    JSONObject userJson=new JSONObject();
    try {
        userJson.put("country","IN");
        userJson.put("number","9620494812");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        postData.put("username" , userJson);
        postData.put("password" , "119209");

    } catch (JSONException e) {
        e.printStackTrace();
    }

技术

company_id | name      | temp
-----------------------------
         1 | Sony      |    1
         2 | Samsung   |    0
         3 | Apple     |    1

在这两个表中,您会看到公司表中不存在技术表中ID为6和7的公司。 我需要选择它们并将其插入到公司表中。

我尝试了很多东西,但却陷入了更多的困境:P

我尝试的最后一件事是:

technology_id | company_id
--------------------------
            1 |          2
            2 |          1
            3 |          1
            4 |          3
            5 |          6
            6 |          7

但是使用这段代码我得到了这个输出: 1 2 ... 1403 1 2 ... 1403 ...

1403是我公司表中的记录数量

3 个答案:

答案 0 :(得分:5)

您可以尝试在数据库中进行此类工作

select * from technologies where company_id not in ( select company_id from companies )

答案 1 :(得分:4)

要获取其他表中不存在的记录,只需使用简单的左连接,无需多次查询

select t.*
from technologies  t
left join companies c on t.company_id = c.company_id
where c.company_id is null

答案 2 :(得分:-1)

  • 在公司表的company_id字段中添加新约束-id它不存在 -

  • 从技术表中获取数据并迭代其行。在公司表中插入行

  • 注意将所有代码和迭代代码放在try {} catch(){}