[英]Get distinct column values based on composite primary key
I've a table such that : 我的桌子是这样的:
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
And finally a table of their mapping 最后是他们的映射表
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
etc.. 等等..
Now I made a query to get : (looping through each type_id) 现在我进行查询以获取:(遍历每个type_id)
for type_id = 1, I'm getting : 对于type_id = 1,我得到:
resource_id | type_id
---------------------
1 | 1
1 | 1
1 | 1
while I wish to get only one row 我只想排一排
Similarly 同样
for type_id = 2 对于type_id = 2
I am getting : 我正进入(状态 :
resource_id | type_id
---------------------
2 | 1
2 | 1
2 | 1
2 | 2
2 | 2
while I wish to get only 2 rows : ie 而我只希望得到两行:即
resource_id | type_id
---------------------
2 | 1
2 | 2
.. and so on .. 等等
This is my query : 这是我的查询:
$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 );
I also tried : (in ref to : http://ellislab.com/forums/viewthread/57781/ ) 我也尝试过:(参考: 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 );
But distinct doesn't work and I get : You have an error in your SQL syntax; 但是,distinct无效,我得到:SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax.
查看与您的MySQL服务器版本相对应的手册以获取正确的语法。
In first query use group-ing: Group by resource_id, type_id 在第一个查询中使用分组:分组按resource_id,type_id
This will limit count of result lines. 这将限制结果行的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.