Php 基于复合主键获取不同的列值
我有一张这样的桌子:Php 基于复合主键获取不同的列值,php,mysql,codeigniter,activerecord,phpactiverecord,Php,Mysql,Codeigniter,Activerecord,Phpactiverecord,我有一张这样的桌子: table : resource resource_id | name ------------------ 1 | res1 2 | res2 table : type type_id | name --------------- 1 | type1 2 | type2 table : action action_id | name ----------------- 1 | re
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
等等
现在我做了一个查询以获取:(循环遍历每个类型的\u id)
对于类型_id=1,我得到:
resource_id | type_id
---------------------
1 | 1
1 | 1
1 | 1
resource_id | type_id
---------------------
2 | 1
2 | 1
2 | 1
2 | 2
2 | 2
而我只想得到一排
同样地
对于类型_id=2
我得到:
resource_id | type_id
---------------------
1 | 1
1 | 1
1 | 1
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 );
我还尝试:
(参考:)
但distinct不起作用,我得到:
您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以了解正确的语法。在第一个查询中,请使用组: 按资源\u id、类型\u id分组 这将限制结果行的计数