2016-06-28 104 views
0

我在我的數據庫中有三個表格,一個用於存儲用戶詳細信息,一個用於存儲團隊詳細信息,另一個用於存儲用戶和團隊ID以識別哪個團隊屬於用戶。如何正確使用此查詢?

我現在想從DB中獲取屬於所選組的所有用戶。而我做的是這樣的:

SELECT u.name, u.image FROM groups g, user_groups ug, users u WHERE 
g.id = ? AND ug.group_id = g.id 

enter image description here

,但我沒有得到結果我想要的。正如你可以在上面附加的圖片看,我有兩個一組的用戶,所以我在我的迴應期待兩項紀錄,但是這是我得到響應:

JSON response:

{ 
    "error": false, 
    "users": [ 
    { 
     "name": "Dušan Dimitrijević", // This is the user from selected group, but i'm getting duplicate record 
     "image": "http://192.168.42.6:8081/timster/uploads/user_images/%2018.png" 
    }, 
    { 
     "name": "Dušan Dimitrijević", 
     "image": "http://192.168.42.6:8081/timster/uploads/user_images/%2018.png" 
    }, 
    { 
     "name": "Miroslav", // And this one too, but also duplicated 
     "image": "null" 
    }, 
    { 
     "name": "Miroslav", 
     "image": "null" 
    }, 
    { 
     "name": "Pera Peric", 
     "image": "null" 
    }, 
    { 
     "name": "Pera Peric", 
     "image": "null" 
    }, 
    { 
     "name": "Marko Markovic", 
     "image": "null" 
    }, 
    { 
     "name": "Marko Markovic", 
     "image": "null" 
    }, 
    { 
     "name": "Stefan Dimitrijevic", 
     "image": "null" 
    }, 
    { 
     "name": "Stefan Dimitrijevic", 
     "image": "null" 
    }, 
    { 
     "name": "Petar Nikolic", 
     "image": "null" 
    }, 
    { 
     "name": "Petar Nikolic", 
     "image": "null" 
    }, 
    { 
     "name": "Nikola Ristic", 
     "image": "null" 
    }, 
    { 
     "name": "Nikola Ristic", 
     "image": "null" 
    } 
    ] 
} 

所以,我想我在查詢SELECT中做錯了什麼。

+0

名稱,圖像,用戶,組。我不知道你在說什麼。 – Strawberry

+0

用戶屬於兩個組,這就是爲什麼。如果修改查詢以在結果中包含組標識,您將看到結果實際上不是重複的 – dimlucas

+0

您應該刪除'ug'表。並把你的兩個人的鏈接放在用戶數據庫中。然後,你將能夠執行'u.group_id = g.id'來只讀取相關的團隊 – tektiv

回答

5

我認爲你正在實現你的關係錯誤,你應該根據用戶ID加入user_group表。

而且也,你應該考慮使用JOIN聲明:(?我認爲你USER_GROUP表有一個user_id的字段)

SELECT 
    u.name, 
    u.image 
FROM 
    users u 
INNER JOIN 
    user_groups ug 
    ON ug.user_id = u.id 
WHERE 
    ug.group_id = ? 

+0

是的,它有。讓我試試這個。 –

+0

就是這樣,先生。欣賞! –

0

做不同的表之間的SELECT查詢是這樣的:

SELECT * FROM table1,table2,table3 

這是做表(= CROSS JOIN)之間的笛卡爾乘積。這將複製大量數據,以製作包含不同表格的所有可能組合的表格。

查看有關CROSS一些文檔JOIN here

在你的情況,你應該使用INNER JOIN,這是更apropriate。