带有codeigniter的where子句中的条件

时间:2016-01-18 06:30:12

标签: mysql codeigniter

我的表结构是

CREATE TABLE `emp_bank` (
  `bank_id` int(11) NOT NULL,
  `emp_id` int(11) NOT NULL,
  `bank_name` int(11) NOT NULL COMMENT 'pk from emp_bank_name tb',
  `branch_name` varchar(100) NOT NULL,
  `ac_num` varchar(100) NOT NULL,
  `ac_holdername` varchar(100) DEFAULT NULL,
  `ac_type` varchar(50) NOT NULL,
  `routing_num` varchar(50) NOT NULL,
  `pay_mode` varchar(100) NOT NULL,
  `ac_active` varchar(5) NOT NULL,
  `type` tinyint(4) DEFAULT NULL COMMENT '1=personal ac, 2=salary ac'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我想从此表中选择所有数据。我的条件是,如果type = 2不存在,则选择type = 2的所有数据,然后选择type = 1

的所有数据

表格数据:

 INSERT INTO `emp_bank` (`bank_id`, `emp_id`, `bank_name`, `branch_name`, `ac_num`, `ac_holdername`, `ac_type`, `routing_num`, `pay_mode`, `ac_active`, `type`) VALUES
(21, 32, 8, 'Statue', '3301000400020423', 'Adarsh', 'Salary Savings', 'PUNB00023', 'Online', '1', 1),
(32, 66, 16, 'er', '43243', 'd3f', 'Salary Savings', '34', '34', '1', 1),
(33, 66, 23, 'fewr', '234', 'def', 'Current', 'er4', 'fdf', '1', 2),
(34, 68, 24, 'wer', '12323', 'erer', 'Savings', '4234', 'wer', '1', 1),
(35, 68, 25, 'wer', 'w434', 'ewr34', 'Savings', 'er', 'rwer', '1', 2),
(38, 75, 27, 'hn', '1234', 'dd', 'Savings', 'dd3', 'dd', '1', 1),
(39, 75, 8, 'ktm', '123', 'dd', 'Salary Savings', 'dd2', 'dd', '1', 2);

2 个答案:

答案 0 :(得分:1)

试试这个

<?php
// get type 2 data
$query = $this->db->query("SELECT * FROM emp_bank WHERE type = 2");
$result = $query->result_array();
$count = count($result); // get count

if (!empty($count)) {
    // Type 2 have data
    return $result;
}
else{
    // Type 2 dont have any data. So getting data from Type 1
    $query1 = $this->db->query("SELECT * FROM emp_bank WHERE type = 2");
    $result1 = $query->result_array();
    return $result1;
}

答案 1 :(得分:0)

这是一个生成结果集的查询:

SELECT *
FROM emp_bank
WHERE ((SELECT COUNT(*) FROM emp_bank WHERE type = 2) > 0 AND type = 2) OR
    ((SELECT COUNT(*) FROM emp_bank WHERE type = 2) = 0 AND type = 1)

这是PHP代码:

$where_clause = "((SELECT COUNT(*) FROM emp_bank WHERE type = 2) > 0 AND type = 2)";
$where_clause .= " OR ((SELECT COUNT(*) FROM emp_bank WHERE type = 2) = 0 AND type = 1)";

$this->db->select("*)
->from("emp_bank")
->where($where_clause);