1

Есть таблицы:

  • профиля пользователя - cmd_site_userprofile_imeiid
  • устройств - gwcsu
  • истории устройств - history

Нужно выбрать все устройства для пользователя и последнюю историческую запись для устройства. Выбираю все устройства для пользователя:

SELECT "gwcsu"."id",
"gwcsu"."imei",
"gwcsu"."description",
"gwcsu"."lastContainerName"
FROM "gwcsu"
INNER JOIN "cmd_site_userprofile_imeiid" ON ("gwcsu"."id" = "cmd_site_userprofile_imeiid"."gwcsu_id")
WHERE "cmd_site_userprofile_imeiid"."userprofile_id" = 19

Потом для каждого устройства выбираю последнюю по времени историческую запись удовлетворяющую условиям, связь истории и устройства по "history"."imeiId" = "gwcsu"."imei":

SELECT "history"."id",
"history"."imeiId",
"history"."dateTime",
"history"."latitude",
"history"."longitude",
FROM "history"
WHERE ("history"."imeiId" = 1
AND NOT ("history"."latitude" IS NULL)
AND NOT ("history"."longitude" IS NULL)
AND NOT ("history"."dateTime" IS NULL))
ORDER BY "history"."dateTime" DESC
LIMIT 1

Такой вариант работает, но долго, скажите возможно ли эти два запроса сделать одним (быстрым)? Пробовал сделать так:

SELECT
"gwcsu"."id",
"gwcsu"."imei",
"gwcsu"."description",
"gwcsu"."lastContainerName",
(
    SELECT "history"."imeiId", "history"."latitude" FROM "history"
    WHERE
        (
            "history"."imeiId" = "gwcsu"."id"
            AND not("history"."latitude" IS NULL)
            AND not("history"."longitude" IS NULL)
            AND not("history"."dateTime" IS NULL)
        )
    ORDER BY "history"."dateTime" DESC LIMIT 1
)
FROM "gwcsu" INNER JOIN "cmd_site_userprofile_imeiid" ON
    ("gwcsu"."id" = "cmd_site_userprofile_imeiid"."gwcsu_id")
WHERE
    "cmd_site_userprofile_imeiid"."userprofile_id" = 19

Но получаю ошибку "ERROR: subquery must return only one column"

UPD. По совету @Denis сделал так:

SELECT
"gwcsu"."id",
"gwcsu"."imei",
"gwcsu"."description",
"gwcsu"."lastContainerName",
(
    SELECT "history"."latitude" FROM "history"
    WHERE
    (
        "history"."imeiId" = "gwcsu"."id"
        AND not("history"."latitude" IS NULL)
        AND not("history"."longitude" IS NULL)
        AND not("history"."dateTime" IS NULL)
    )
    ORDER BY "history"."dateTime" DESC LIMIT 1
),
(
    SELECT "history"."longitude" FROM "history"
    WHERE
    (
        "history"."imeiId" = "gwcsu"."id"
        AND not("history"."latitude" IS NULL)
        AND not("history"."longitude" IS NULL)
        AND not("history"."dateTime" IS NULL)
    )
    ORDER BY "history"."dateTime" DESC LIMIT 1
),
(
    SELECT "history"."dateTime" FROM "history"
    WHERE
    (
        "history"."imeiId" = "gwcsu"."id"
        AND not("history"."latitude" IS NULL)
        AND not("history"."longitude" IS NULL)
        AND not("history"."dateTime" IS NULL)
    )
    ORDER BY "history"."dateTime" DESC LIMIT 1
)
FROM "gwcsu" INNER JOIN "cmd_site_userprofile_imeiid" ON
    ("gwcsu"."id" = "cmd_site_userprofile_imeiid"."gwcsu_id")
WHERE
    "cmd_site_userprofile_imeiid"."userprofile_id" = 19

Выглядит конечно громоздко, но работает.

1
  • Попробуйте лучше первый запрос, и в него добавьте все эти столбцы. Обновил ответ.
    – Denis
    18 мая 2017 в 19:48

1 ответ 1

0

Конечно будет ошибка, потому что вы в 1 столбец хотите записать и "history"."imeiId", и "history"."latitude".

Попробуйте так:

SELECT
   "gwcsu"."id",
   "gwcsu"."imei",
   "gwcsu"."description",
   "gwcsu"."lastContainerName",
   "h"."imeiId",
   "h"."latitude",
   "h"."longitude",
   "h"."dateTime"
FROM "gwcsu" JOIN "cmd_site_userprofile_imeiid" ON
         ("gwcsu"."id" = "cmd_site_userprofile_imeiid"."gwcsu_id")
    JOIN (SELECT "history"."imeiId", "history"."latitude",
             "history"."longitude",
             "history"."dateTime"
          FROM "history"
          WHERE
          (
            AND not("history"."latitude" IS NULL)
            AND not("history"."longitude" IS NULL)
            AND not("history"."dateTime" IS NULL)
          )
          ORDER BY "history"."dateTime" DESC LIMIT 1) "h" ON "h"."imeiId" = "gwcsu"."id"
WHERE
    "cmd_site_userprofile_imeiid"."userprofile_id" = 19

Либо исправьте ваш запрос:

SELECT
"gwcsu"."id",
"gwcsu"."imei",
"gwcsu"."description",
"gwcsu"."lastContainerName",
(
    SELECT "history"."latitude" FROM "history"
    WHERE
        (
            "history"."imeiId" = "gwcsu"."id"
            AND not("history"."latitude" IS NULL)
            AND not("history"."longitude" IS NULL)
            AND not("history"."dateTime" IS NULL)
        )
    ORDER BY "history"."dateTime" DESC LIMIT 1
)
FROM "gwcsu" INNER JOIN "cmd_site_userprofile_imeiid" ON
    ("gwcsu"."id" = "cmd_site_userprofile_imeiid"."gwcsu_id")
WHERE
    "cmd_site_userprofile_imeiid"."userprofile_id" = 19
1
  • большое спасибо!
    – avig
    18 мая 2017 в 18:39

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.