2011-07-03 43 views
-1

數據我有兩個表:EmployeeInfo表(表1),並ItemsInfo表(表2):MySQL查詢:使用連接來獲得不結果好

表1:

enter image description here

表2:

enter image description here

在UI畫面,我有兩個DIV層 - 左格和右格。左邊的div應該加載沒有關聯到員工的數據,右邊的div應該加載與員工相關的數據。

例如,在頁加載,用於與EMPID = 201僱員,在這兩種DIV數據應被填充這樣的: enter image description here

爲了實現這一點,我想MySQL查詢輸出是這樣的:

enter image description here

被返回的JSON對象輸出是這樣的:

[{"empid":"","itemid":"1","items":"Apple"},{"empid":"201","itemid":"2","items":"Banana"},{"empid":"","itemid":"3","items":"Baseball"},{"empid":"","itemid":"4","items":"Bikes"},{"empid":"201","itemid":"5","items":"Blue"}] 

因此,我可以用getJson方法將數據推送到適當的div。如果empid = null,則要將數據推送到左側div中,如果empid = 201,則將數據推送到右側div。

我試着用左連接,但是,因爲在表1中,所有的字段值重複多次,我沒有得到確切的查詢輸出。

請幫助我如何實現上述場景..在此先感謝。

回答

1

你的問題是有點硬了所有你在扔東西的用戶界面讀取爲了讓您的請求的查詢輸出做:

select t1.empid, t2.itemid, t2.items 
    from Itemsinfo t2 left join EmployeeInfo t1 on t1.itemid=t2.itemid and empid=201; 
+0

而你爲什麼不規範化你的架構一點?你可以扔掉EmployeeInfo.items ... – ivy

+0

謝謝你..亞,現在我規範化表1通過刪除它的項目。最後,這裏是我結束並完美的工作:從t2.itemid選擇t2.itemid,t2.items,t1.empid,t2.itemid = t1.itemid和empid = 201 – prajan

0

最終,我與一些指導修好了我自己@常春藤。這裏是查詢得到確切的輸出:

select t2.itemid, t2.items, t1.empid from t2 left join t1 on t2.itemid=t1.itemid and empid=201