我在我的數據庫中有三個表格,一個用於存儲用戶詳細信息,一個用於存儲團隊詳細信息,另一個用於存儲用戶和團隊ID以識別哪個團隊屬於用戶。如何正確使用此查詢?
我現在想從DB中獲取屬於所選組的所有用戶。而我做的是這樣的:
SELECT u.name, u.image FROM groups g, user_groups ug, users u WHERE
g.id = ? AND ug.group_id = g.id
,但我沒有得到結果我想要的。正如你可以在上面附加的圖片看,我有兩個一組的用戶,所以我在我的迴應期待兩項紀錄,但是這是我得到響應:
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中做錯了什麼。
名稱,圖像,用戶,組。我不知道你在說什麼。 – Strawberry
用戶屬於兩個組,這就是爲什麼。如果修改查詢以在結果中包含組標識,您將看到結果實際上不是重複的 – dimlucas
您應該刪除'ug'表。並把你的兩個人的鏈接放在用戶數據庫中。然後,你將能夠執行'u.group_id = g.id'來只讀取相關的團隊 – tektiv