SQL查询同一张表两次,但只获得一个输出列mysql

时间:2019-02-06 15:20:26

标签: mysql sql

我需要列出与RELATIONS表中的每个SOURCE / ACCOUNT对相关的两个ENTITY_ID(通过使用两个日期之间的WHERE查询RELATIONS表)。

- 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

下面的查询检索一个SOURCE / ACCOUNT对(SOURCE_1 / ACCOUNT_1)的ENTITY_ID,但是我还需要SOURCE_2 / ACCOUNT_2的ENTITY_ID,而不是输出中的第二列,而是第二行(值)

SELECT A.ENTITY_ID
  FROM RELATIONS R
  JOIN ACCOUNTS A
    ON R.SOURCE_1  = A.SOURCE
   AND R.ACCOUNT_1 = A.ACCOUNT
 WHERE R.TIMESTAMP >= DATETIME1 AND R.TIMESTAMP < DATETIME2         

需要的输出示例(1列,2个值):

                    ENTITY_ID
Output record #1    1234
Output record #2    1235

1 个答案:

答案 0 :(得分:0)

如果需要不同行中的值,则可以执行以下操作:

    sharedPreferences = getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
    String hexColor = sharedPreferences.getString("toolbarColor", "");
    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(hexColor)));

SELECT A.ENTITY_ID FROM RELATIONS R JOIN ACCOUNTS A ON (R.SOURCE_1 = A.SOURCE AND R.ACCOUNT_1 = A.ACCOUNT ) OR (R.SOURCE_2 = A.SOURCE AND R.ACCOUNT_2 = A.ACCOUNT ) WHERE R.TIMESTAMP >= DATETIME1 AND R.TIMESTAMP < DATETIME2; 通常会削弱OR的性能,但是如果您的数据不是很大,这将起作用。