2010-02-24 58 views
1

不能讓我的頭圍繞這個...SQL:從多對多通過選擇,在加入了條件通過表

我有3個表是這樣的:

Computers 
--------- 
Id 
Name 


ComputerLogins 
-------------- 
Computer_Id 
User_Id 
NumberOfLogins 


Users 
----- 
Id 
Name 

計算機「有並通過「ComputerLogins」屬於許多「用戶」。

的樣本數據:

Computers:     Id  Name 
          1 "Alpha" 
          2 "Beta" 
          3 "Gamma" 

Users:      Id  Name 
          1 "Joe" 
          2 "Fred" 

ComputerLogins: Computer_Id User_Id NumberOfLogins 
          1  1    5 
          1  2    12 
          2  1    10 
          2  2    6 
          3  1    2 
          3  2    4 

我試圖構建一個視圖,將輸出一行在計算機的每個記錄,並加入一個用戶通過MAX(NumberOfLogins)在ComputerLogins行。

所需的輸出:

Computer_Id User_Id NumberOfLogins 
      1   2    12 
      2   1    10 
      3   2     4 

你可以建議將產生所需的輸出視圖的查詢? 謝謝!

回答

1
SELECT 
    CL.*, U.* --change this as needed 
FROM 
    (
    SELECT 
     Computer_ID, MAX(NumberOfLogins) AS NumberOfLogins 
    FROM 
     ComputerLogins 
    GROUP BY 
     Computer_ID 
    ) maxC 
    JOIN 
    ComputerLogins CL On maxC.Computer_ID = CL.Computer_ID AND maxC.NumberOfLogins = CL.NumberOfLogins 
    JOIN 
    Users U On CL.User_ID = U.ID 

裹在一個視圖等

+0

的偉大工程!非常感謝! –

1

用途:

CREATE VIEW your_view AS 
SELECT c.id AS computer_id, 
     u.id AS user_id, 
     COUNT(*) AS NumberOfLogins 
    FROM COMPUTERS c 
    JOIN COMPUTERLOGINS cl ON cl.computer_id = c.id 
    JOIN USERS u ON u.id = cl.user_id 
GROUP BY c.id, u.id