basic many-to-many sql select query

后端 未结 9 1813
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-17 03:06

I think this should be easy, but it\'s evading me. I\'ve got a many-to-many relationship between Accounts and Account Groups. An Account can be in zero or more Groups, so I\

相关标签:
9条回答
  • 2021-01-17 03:35

    Another thought... why not use the Query Designer in Access. This should take about 30 seconds to design the "View". Then go look at the SQL it wrote.

    0 讨论(0)
  • 2021-01-17 03:39

    SQL Server uses ISNULL() for that purpose. I'm not sure whether that works in Access.

    0 讨论(0)
  • 2021-01-17 03:44

    Yeah, I'll use the presentation layer for the NULL.

    But I must be missing something. I'm getting the same error from yours as from my original attempts:

    Syntax error (missing operator) in query expression '(act.id = jag.aid) 
                      LEFT OUTER JOIN accountgroups gp ON (jag.gid = gp.id)'
    
    0 讨论(0)
  • 2021-01-17 03:46
    SELECT act.acctid AS AcctId, bankName, acctNumber, Balance, 
           NVL(jag.gid, '-') AS GroupID, NVL(gp.groupname, '-') AS GroupName
    FROM accounts act 
         LEFT OUTER JOIN JointAccountGroups jag ON (act.id = jag.aid) 
         LEFT OUTER JOIN AccounGroups gp ON (jag.gid = gp.id)
    

    NVL is a function that means "if first argument is null, return the second argument; otherwise, return first argument". NVL happens to be how Oracle do it -- all DBs have something like that, but it doesn't have a standard name; look up how Access does it.

    0 讨论(0)
  • 2021-01-17 03:46

    How about:

    SELECT act.acctid AS AcctId, bankName, acctNumber, Balance, 
          jag.gid AS GroupID, gp.groupname AS GroupName
    FROM accounts AS act 
         LEFT OUTER JOIN JointAccountGroups AS jag ON act.id = jag.aid
         LEFT OUTER JOIN AccounGroups AS gp ON jag.gid = gp.id
    

    Does this give you an error? An error that is easier to figure out perhaps?

    0 讨论(0)
  • 2021-01-17 03:51

    This

    SELECT a.BankName, a.AcctNumber, a.Balance, ag.GroupName
    FROM (Accounts a 
          LEFT JOIN JoinAccountsGroups jag 
          ON a.ID = jag.AID) 
          LEFT JOIN AccountGroups ag
          ON jag.GID = ag.GroupName;
    

    Will select the data for the first table, however to concatenate the groups (Monthly, Payroll), you would need a User Defined Function (UDF), wich would not be available to Jet, so processing in PHP would be necessary.

    You may wish to read Understanding SQL Joins. It refers to MySQL but applies to Jet, for the most part.

    0 讨论(0)
提交回复
热议问题