CodeIgniter连接字符串不等于操作

时间:2017-12-10 14:47:35

标签: php mysql database codeigniter

我有两张桌子:

表1:

CREATE TABLE `users` (
  `user_id` int(255) NOT NULL,
  `user_name` varchar(100) NOT NULL,
  `user_email` varchar(100) NOT NULL,
  `user_password` varchar(200) NOT NULL,
  `user_phone` varchar(20) NOT NULL,
  `building_units` int(200) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `status` enum('0','1') NOT NULL DEFAULT '1' COMMENT '1 = Active(default), 0 = Inactive',
  `user_role` enum('0','1','2','3') NOT NULL DEFAULT '2' COMMENT '0=Manager,1=Admin,2=User,3=Tenant',
  `user_ip` int(39) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

表2:

CREATE TABLE `building_admins_tbl` (
  `id` int(255) NOT NULL,
  `building_id` int(255) NOT NULL COMMENT 'FK ',
  `building_admin_id` int(255) DEFAULT NULL COMMENT 'FK',
  `user_id` int(255) DEFAULT NULL,
  `tenant_id` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我写了以下查询:

$select = 'users.user_id,users.user_name,users.user_role,users.status,building_admins_tbl.building_admin_id';
$join_str = 'users.user_id != building_admins_tbl.building_admin_id';
$where = ['users.user_role'=>'1','users.status'=>'1'];

        $q =$this->db    
                    ->select($select)
                    ->where($where)
                    ->from('users')    
                    ->join('building_admins_tbl',$join_str)
                    ->get();
        $admin_list =$q->result_array();

在上面的查询中,连接字符串很重要。我想只获得那些带有where条件的行where(users.user_id != building_admins_tbl.building_admin_id)

但我没有得到期待的结果。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

我不确定你应该加入什么,因为你没有正确设置你的外键,如果你这样做了,你没有包含这些信息,但是我会试一试,因为真正的答案是你想要进行连接,但使用不同的WHERE子句。

你必须真正加入另一张桌子,你不能使用!=:

// This looks like you are trying to join on the admin ID, which is probably wrong
$join_str = 'users.user_id = building_admins_tbl.building_admin_id';

// If you are trying to get tenants, it's probably supposed to be:
$join_str = 'users.user_id = building_admins_tbl.tenant_id';

// If you are trying to join with the users table, it might be:
$join_str = 'users.user_id = building_admins_tbl.user_id';

但请确保您不包括管理员

$where = [
    'users.user_role !=' => '1', // Do not include user role #1 (admins)
    'users.status'       => '1'
];

答案 1 :(得分:0)

插入后只需加载您的视图页

并在您的视图页面中添加这些行

$this->output->enable_profiler(TRUE); //在php标签内

这些将在您的视图中为您提供原始查询,只需复制查询并在phpmyadmin中执行它

答案 2 :(得分:0)

我找到了答案。

    $q = $this->db
            ->from('users')
            ->where(['user_role'=>'1'])
            ->where(['status'=>'1'])
            ->where("
              NOT EXISTS (
                select building_admin_id from building_admins_tbl where  users.user_id = building_admins_tbl.building_admin_id)") 
            ->get();
    $data['admins_list'] = $q->result_array();