选择联接两个表并循环以获取两个不同的值

时间:2019-02-06 13:08:38

标签: mysql sql

我需要查询RELATIONS表(两个日期之间的位置),并在RELATIONS表中获取与每个SOURCE / ACCOUNT对相关的ENTITY_ID。

m.get("org.apache.cxf.resource.method")

是否可以在一个查询中执行此操作?

查询的输出应如下所示:

null

我对如何获得ENTITY_ID_1有一个想法,但不确定如何同时获得ENTITY_ID_2。

- ENTITIES table
ENTITY_ID (PK)
ENTITY_NAME

    - ACCOUNTS table
    SOURCE    (PK)
    ACCOUNT   (PK)
    ENTITY_ID (FK)

        - RELATIONS table
        RELATION_ID (PK)
        SOURCE_1    (FK)
        ACCOUNT_1   (FK)
        SOURCE_2    (FK)
        ACCOUNT_2   (FK)
        TIMESTAMP

欢迎对此问题有一个更好的标题的想法。

1 个答案:

答案 0 :(得分:0)

我认为您只需要两个JOIN

SELECT R.RELATION_ID, R.SOURCE_1, R.ACCOUNT_1,
       A1.ENTITY_ID AS ENTITY_ID_1, 
       A2.ENTITY_ID AS ENTITY_ID_2, 
       R.SOURCE_2, R.ACCOUNT_2
FROM RELATIONS R JOIN
     ACCOUNTS A1
     ON R.SOURCE_1  = A1.SOURCE AND
        R.ACCOUNT_1 = A1.ACCOUNT JOIN
     ACCOUNT A2
     ON R.SOURCE_2  = A2.SOURCE AND
        R.ACCOUNT_2 = A2.ACCOUNT
WHERE R.TIMESTAMP >= DATETIME1 AND
      R.TIMESTAMP < DATETIME2