【问题标题】:how to get value which not in table 2如何获得不在表 2 中的值
【发布时间】:2013-10-07 09:25:50
【问题描述】:

如何获取不在 table_2 中的 table_1 id
我的桌子看起来像这种类型。
table_1

---------------------------------------------
|  id      |    user                        |
---------------------------------------------
|   1      |    Jack                        |
---------------------------------------------
|   2      |    John                        |
---------------------------------------------

table_2

------------------------------------------
|  web_id      |    website              |
------------------------------------------
|   2          |   Facebook              |
------------------------------------------
|   3          |   Google+               |
------------------------------------------

我想codeigniter查询

$this->db->select("*");
        $this->db->from("table_1");
        $this->db->where_not_in('id', "table_2.web_id");
        return $this->db->get();

【问题讨论】:

  • 这两张表有什么关系?
  • 我认为 id 和 web_id
  • 我在下面添加了两种方式的查询

标签: php sql codeigniter


【解决方案1】:

试试这个

 SELECT id
 FROM table_1
 WHERE id NOT IN
 (
       SELECT web_id FROM table_2 WHERE 1
 );

使用 CodeIgniter Active Records 查询如下

  $this->db->select('*');
  $this->db->where('id NOT IN (SELECT web_id FROM table_2 WHERE 1)', NULL, FALSE);
  $query = $this->db->get('table_1');

【讨论】:

    【解决方案2】:

    这样就可以了(取决于您使用的 SQL 的风格,您可能需要稍微调整语法):

    SELECT id
    FROM table_1
    WHERE id NOT IN (SELECT web_id FROM table_2)
    

    但是,我看不出这有什么用。这两个表之间没有可识别的链接,因此知道 table_1 中有一个 1 的 id 但 table_2 中没有 1 的 web_id 似乎不是有用的信息。

    【讨论】:

    • 是的,它的核心查询,但是当我在 codeigniter 上尝试这个查询时,你能告诉我这个查询有什么问题吗$this->db->select("*"); $this->db->from($this->_table); $this->db->where_not_in('id', $this->_tuple.".tuple_regexs_id"); return $this->db->get();
    • @user2846831 我不会用 PHP 编写代码,所以不,我不能告诉你这有什么问题。如果您遇到的 PHP 代码有问题,那么您需要在问题中明确说明(并确保包含代码的相关部分!),因为现在它显示为“要执行的 SQL 是什么这个?”
    【解决方案3】:
    select t1.id
    from table_1 t1
    left join table_2 t2 on t1.id = t2.web_id
    where t2.web_id is null
    

    【讨论】:

      猜你喜欢
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多