任何人都可以帮我修复我的SQL查询吗?

时间:2016-12-10 03:10:00

标签: mysql sql

在我的数据库中存在多个表,其中6个是类别表; baby_care,杂货店,medical_equipment,medical_supply,medicine和personal_care (请注意命名惯例,因为这是我们的学校项目,我们仍然是学生)。

我想查询他们的lotno和description属性(具有不同的名称,如med_lotno等)以及来自其他表(如item_list和received_item)的名称和数据。我需要单行查询,因为我们已经观察到, jasperreport 查询只接受一行查询。

所以我尝试了这个查询:

SELECT
all_items.il_code, 
"" & med_lotno & ms_lotno & pc_lotno & bc_lotno & gi_lotno as lotno, 
all_items.sup_name, 
me_description &  med_item_description & ms_item_description & pc_item_description & bc_description & gi_item_description as description, 
"" & med_expdate & ms_expdate & pc_expdate & bc_expdate & gi_expdate as expiration_date, 
all_items.ri_unit_quantity, 
all_items.ri_date from 
((((((select il_code from item_list union 
select sup_name from supplier union 
select ri_unit_quantity, ri_date from received_item) as all_items 
left join medical_equipment ON (all_items.il_code = medical_equipment.il_code))
left join medicine ON (all_items.il_code = medicine.il_code)) 
left join medical_supply ON (all_items.il_code = medical_supply.il_code))
left join personal_care ON (all_items.il_code = personal_care.il_code))
left join baby_care ON (all_items.il_code = baby_care.il_code))
left join grocery ON (all_items.il_code = grocery.il_code);

但它给了我一个错误

  

" java.sql.SQLException:使用的SELECT语句具有不同的列数"

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我现在正在浏览sql,但我想我找到了抛出这个特定错误的精确部分。 union语句需要每个select具有相同数量的列,其中一个具有两个。见下文。

SELECT
    all_items.il_code, 
    "" & med_lotno & ms_lotno & pc_lotno & bc_lotno & gi_lotno as lotno, 
    all_items.sup_name, 
    me_description &  med_item_description & ms_item_description & pc_item_description & bc_description & gi_item_description as description, 
    "" & med_expdate & ms_expdate & pc_expdate & bc_expdate & gi_expdate as expiration_date, 
    all_items.ri_unit_quantity, 
    all_items.ri_date 
FROM
(
  select il_code from item_list union
  select sup_name from supplier union
  select ri_unit_quantity, ri_date from received_item #<---This select here has two columns while the other selects in the union have only one.
) as all_items 
left join medical_equipment ON all_items.il_code = medical_equipment.il_code
left join medicine ON all_items.il_code = medicine.il_code
left join medical_supply ON all_items.il_code = medical_supply.il_code
left join personal_care ON all_items.il_code = personal_care.il_code
left join baby_care ON all_items.il_code = baby_care.il_code
left join grocery ON all_items.il_code = grocery.il_code;

如果不真正更改查询功能,可以将联合选择更改为:

select il_code, "" from item_list union
select sup_name, "" from supplier union
select ri_unit_quantity, ri_date from received_item

这样它们都具有相同数量的列,唯一的缺点是结果表中会有一些空字段。不可否认,我从未见过以这种特殊方式嵌套的左连接。