簡體   English   中英

根據復合主鍵獲取不同的列值

[英]Get distinct column values based on composite primary key

我的桌子是這樣的:

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

而我只希望得到兩行:即

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服務器版本相對應的手冊以獲取正確的語法。

在第一個查詢中使用分組:分組按resource_id,type_id

這將限制結果行的數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM