在UNION ALL视图创建中使用JOIN

时间:2019-06-06 13:12:21

标签: sql ruby-on-rails postgresql

我正在创建一个合并两个表的视图,这两个表具有一些相似的字段和一些不同的字段。我的95%工作正常,但是表A中的一个字段与表B中的一个字段匹配,但前提是您使用表B中的该字段作为联接从表C中提取一个字段。不起作用的是JOIN。我可以将两个字段都放入其中,并执行从模型中的provider_id中获取ehruser_id的逻辑,但是我觉得它应该在SQL中是可行的,但是我没有使最后一点起作用的知识

DROP VIEW IF EXISTS vunifiedschedule CASCADE;
CREATE VIEW vunifiedschedule AS
SELECT
    schedule_block.id as vid,
    schedule_block.reason as vblock_reason,
    NULL as vappointment_reason_id,
    schedule_block.when_ts as vwhen,
    schedule_block.deleted_ts as vdeleted_when,
    schedule_block.placeofservice_id as vlocation_id,
    schedule_block.duration as vduration,
    true as vappointment_book,
    schedule_block.note as vnote
FROM schedule_block
LEFT JOIN ( SELECT id FROM provider) as vprovider_id ON provider.ehruser_id = schedule_block.ehruser_id
UNION ALL
SELECT
    appointment.id AS vid,
    NULL as vblock_reason,
    appointment.appointmentreason_id AS vappointment_reason_id,
    appointment.appt_when AS vwhen,
    appointment.deleted_when AS vdeleted_when,
    appointment.location_id AS vlocation_id,
    appointment.visit_length AS vduration,
    appointment.appointment_book as vappointment_book,
    appointment.note AS vnote,
    appointment.provider_id as vprovider_id
FROM appointment

我得到的错误是 ERROR: missing FROM-clause entry for table "provider" LINE 14: ...ELECT id FROM provider) as vprovider_id ON provider.e...

3 个答案:

答案 0 :(得分:1)

错误非常明显。您没有http://localhost:4000/my-frontend。我想你打算:

provider

但是子查询是不必要的:

FROM schedule_block LEFT JOIN
     ( SELECT id FROM provider) vprovider_id
     ON vprovider.ehruser_id = schedule_block.ehruser_id
--------^

答案 1 :(得分:1)

  1. 视图的第一个选择stmt有9列,但是第二个选择stmt有10列。该视图将显示错误消息“查询块的结果列数不正确

答案 2 :(得分:0)

您从第一个表中选择了9列,从第二个表中选择了10列,使用并集时,两个查询中的列数必须相同,并且所选类型的列必须匹配。