【发布时间】:2014-04-10 08:56:26
【问题描述】:
我有一张这样的桌子:
table : resource
resource_id | name
------------------
1 | res1
2 | res2
table : type
type_id | name
---------------
1 | type1
2 | type2
table : action
action_id | name
-----------------
1 | read
2 | add
3 | edit
4 | delete
5 | disable
最后是他们的映射表
table : mapping
resource_id | type_id | action_id
------------------------------------
1 | 1 | 1
1 | 1 | 2
1 | 1 | 3
2 | 1 | 1
2 | 1 | 2
2 | 1 | 3
2 | 2 | 4
2 | 2 | 5
等等。
现在我进行了查询以获取:(遍历每个 type_id)
对于 type_id = 1,我得到:
resource_id | type_id
---------------------
1 | 1
1 | 1
1 | 1
虽然我只希望得到一行
同样
对于 type_id = 2
我得到了:
resource_id | type_id
---------------------
2 | 1
2 | 1
2 | 1
2 | 2
2 | 2
虽然我只希望得到 2 行:即
resource_id | type_id
---------------------
2 | 1
2 | 2
..等等
这是我的查询:
$this->db->select ( 'p.resource_id, p.type_id' );
$this->db->from ( 'mapping p' );
$this->db->join ( 'resources r', 'p.resource_id = r.resource_id' );
$this->db->join ( 'type t', 'p.type_id = t.type_id' );
$this->db->where ( 'p.type_id', $typeId );
我也试过: (参考:http://ellislab.com/forums/viewthread/57781/)
$this->db->select ( 'DISTINCT p.resource_id, p.type_id' );
$this->db->from ( 'mapping p' );
$this->db->join ( 'resources r', 'p.resource_id = r.resource_id' );
$this->db->join ( 'type t', 'p.type_id = t.type_id' );
$this->db->where ( 'p.type_id', $typeId );
但 distinct 不起作用,我得到: 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以了解正确的语法。
【问题讨论】:
标签: php mysql codeigniter activerecord phpactiverecord