多表相加同一欄位union聯合的使用

2021-09-11 03:02:02 字數 2587 閱讀 5047

業務需求:

最近的問題就是,有很多部門,部門又擁有商品,商品有不同的品種,我們需要計算出不同部門裡有多少不同商品,

但是對乙個部門來說 既有屬於部門的商品,也有屬於個人的商品,這也就是兩個表,

首先,我們知道,我們需要查的就是部門中同乙個商品,個人持有量和部門持有量。

select

ri_equipmentmessage_sparepart.id,

ri_equipmentmessage_sparepart.`name`,

ri_equipmentmessage_sparepart.model,

ri_equipmentmessage_sparepart.brand,

ri_equipment_sparepart.sparepart_number as number,

ri_equipmentmessage_equipment.department

from

ri_equipment_sparepart

inner join ri_equipmentmessage_sparepart on ri_equipment_sparepart.sparepart_id = ri_equipmentmessage_sparepart.id

inner join ri_equipmentmessage_equipment on ri_equipment_sparepart.equipment_id = ri_equipmentmessage_equipment.id

union all

select

ri_equipmentmessage_sparepart.id,

ri_equipmentmessage_sparepart.`name`,

ri_equipmentmessage_sparepart.model,

ri_equipmentmessage_sparepart.brand,

ri_department_sparepart.number,

ri_department_sparepart.departmentid as department

from

ri_department_sparepart

inner join ri_equipmentmessage_sparepart on ri_department_sparepart.sparepartid = ri_equipmentmessage_sparepart.id

上面是部門持有量,後面是個人持有量,通過union all聯合在一起成為乙個新的表,注意兩個查詢字段順序必須一致,並且資料型別也必須一致,字段可以隱式轉換。

select

id,name,

model,

brand,

sum(number),

department

from

( select

ri_equipmentmessage_sparepart.id,

ri_equipmentmessage_sparepart.`name`,

ri_equipmentmessage_sparepart.model,

ri_equipmentmessage_sparepart.brand,

ri_equipment_sparepart.sparepart_number as number,

ri_equipmentmessage_equipment.department

from

ri_equipment_sparepart

inner join ri_equipmentmessage_sparepart on ri_equipment_sparepart.sparepart_id = ri_equipmentmessage_sparepart.id

inner join ri_equipmentmessage_equipment on ri_equipment_sparepart.equipment_id = ri_equipmentmessage_equipment.id

union all

select

ri_equipmentmessage_sparepart.id,

ri_equipmentmessage_sparepart.`name`,

ri_equipmentmessage_sparepart.model,

ri_equipmentmessage_sparepart.brand,

ri_department_sparepart.number,

ri_department_sparepart.departmentid as department

from

ri_department_sparepart

inner join ri_equipmentmessage_sparepart on ri_department_sparepart.sparepartid = ri_equipmentmessage_sparepart.id

) as a

group by

department,

id

然後,根據部門和id進行分組,就可以了,注意 衍生表必須有 as 表明

Mysql 同一欄位多值模糊查詢

同一欄位多值模糊查詢,使用多個or進行鏈結,效率不高,但沒有更好的解決方案。有看到charindex 關鍵字,可查詢結果並不是模糊,舉個栗子 例如select from table where charindex name 張三,李四 0 二 同一值多字段模糊查詢,使用concat關鍵字,舉個栗子 ...

同一欄位多ID儲存名稱對映

在資料庫設計時,為了減少表儲存的記錄數,對於1對多的關係可以儲存在同乙個記錄中,例如某乙個應用會被多個人使用,有一種儲存方法如下 這樣會造成記錄數會越來越多,還有一種方法可以用2條記錄儲存上述資料 第一種方法的好處就是顯示員工名稱非常方便,和員工資訊表關聯即可 第二種方法如果要顯示維護人員的姓名就非...

多事務併發更新同一字段,引入鎖

總結注意下面的例子 事務1事務2 begin begin select data from test where id 1 得到 ab select data from test where id 1 得到 ab update test set data cb where id 1 update t...