我有一个包含多行的表,这些行具有公共字段值“owner_id”,我希望获得除第一行之外的所有匹配行。因此,查询应返回下面示例表中带有“ID”2,3,5,6的行。
-----------------------
| ID | VALUE | USER_ID |
-----------------------
| 1 | 11111 | 1 |
------------------------
| 2 | 22222 | 1 |
------------------------
| 3 | 33333 | 1 |
------------------------
| 4 | 11111 | 2 |
------------------------
| 5 | 22222 | 2 |
------------------------
| 6 | 33333 | 2 |
------------------------
以下是我获得解决方案之前的代码:
public function get_follow_ups()
{
$this->db->select('a.id, a.created_at, a.user_id, month(b.created_at) AS user_month');
$this->db->from('entries a, users b');
$this->db->order_by('a.created_at');
$this->db->where('a.user_id = b.id');
$this->db->where('day(a.created_at) != day(b.created_at)');
$this->db->where('a.owner_id', $this->_owner_id);
return $this->db->get();
}
有时用户在注册的同一天没有输入,导致在使用此功能时第一个条目包含在查询中。
考虑到创建子查询的想法,我已将函数修改为以下内容:
public function get_follow_ups()
{
$this->db->select('MIN(created_at)')->from('entries')->group_by('user_id');
$subQuery = $this->db->get_compiled_select();
$this->db->select('a.id, a.created_at, a.user_id, month(b.created_at) AS user_month');
$this->db->from('entries a, users b');
$this->db->order_by('a.created_at');
$this->db->where('a.user_id = b.id');
$this->db->where("a.created_at NOT IN ($subQuery)", NULL, FALSE);
$this->db->where('a.owner_id', $this->_owner_id);
return $this->db->get();
}
答案 0 :(得分:3)
您可以按user_id对行进行分组,并为每个组选择min ID。然后选择除先前选择的行之外的所有行。
SELECT * FROM your_table WHERE ID NOT IN (SELECT MIN(ID) FROM your_table GROUP BY USER_ID)