通过使用不同的select into查询将SQL插入到多个列中

时间:2017-01-27 02:08:24

标签: mysql stored-procedures union

我想插入一个包含4列的表格。将使用select into语句填充前两列,而将从两个不同的表填充las两列。我想要做的是所有这些都将逐行填充,没有重复和空值。

要想象我的计划,这是所需的输出:

enter image description here

但每当我尝试这样做时,这就是我得到的:

enter image description here

每个插入的空值。我目前正在使用一个程序,这是我的查询:

CREATE DEFINER=`root`@`localhost` PROCEDURE `Biller`(IN Pid varchar(30))
BEGIN
    insert into sample2(ids,prices)
    select bed_bill_id,price 
    from bed_billing
    where patient_id = Pid
    UNION
    select csr_bill_id,price
    from csr_billing
    where patient_id = Pid
    UNION
    select lab_bill_id,price
    from lab_billing
    where patient_id = Pid
    UNION
    select pharm_bill_id,price
    from pharm_billing
    where patient_id = Pid
    UNION
    select rad_bill_id,price
    from rad_billing
    where patient_id = Pid;

    insert into sample2(patient)
    values(Pid);

    insert into sample2(physician)
    select attending_id
    from attending_physician
    where attending_physician.patient_id = Pid;

END

1 个答案:

答案 0 :(得分:1)

是的,你误解了INSERT的某些内容。每次INSERT,您都会创建行。它不会将数据添加到您最近在先前INSERT语句中创建的行中的更多列。

因此,您需要让患者和医生进入您要插入的行。 Pid很简单,您已将其作为变量,您可以将其作为第三列添加到SELECT中。对于医生,您应该使用JOIN将attnding_physician表中的一列附加到五个结算数据查询联合的列中。

CREATE DEFINER=`root`@`localhost` PROCEDURE `Biller`(IN Pid varchar(30))
BEGIN
    insert into sample2(ids, prices, patient, physician)
    select b.bill_id, b.price, Pid, ph.attending_id
    from (
        select bed_bill_id as bill_id,price 
        from bed_billing
        where patient_id = Pid
        UNION
        select csr_bill_id,price
        from csr_billing
        where patient_id = Pid
        UNION
        select lab_bill_id,price
        from lab_billing
        where patient_id = Pid
        UNION
        select pharm_bill_id,price
        from pharm_billing
        where patient_id = Pid
        UNION
        select rad_bill_id,price
        from rad_billing
        where patient_id = Pid
    ) as b
    cross join attending_physician as ph
    where ph.patient_id = Pid;

END