简体   繁体   中英

Raw SQL query/django query : Get column info by grouping

Following are the tables:

Product Table
25 Tshirt
26 Dress

ProductVariation Table
id product_id variation_id vendor_id
46  26              47        1
47  26              48        1
48  26              49        1
49  27              50        1

Variation Table
id value    attribute_id     category_id     variationinfo_id
47 Female      2                1                17
48 89          3                1                17
49 90          1                1                18
50 #343434     2                1                18

VariationInfo Table
id  stock remarks
17    8     remarks1
18    10    remarks2

Attribute Table
id attribute_name
1   size
2   color
3   gender

Category Table
id name parent remarks
 1 bla  bla    bla

Problem scenario: Product 26 has variation_ids 47, 48, 49. Of these, 47 and 48 have same variationinfo_id 17 and another 49, has 18. For product 26, total stock information is obtained as 18.

However, I need to get distributed stock information for different variationinfo_ids, For example: For variation(VariationTable) 47, 48 with same variationinfo_id of 17, total stock of this variation -> 8 and for 48 with variationinfo_id of 18, total stock of this variation -> 10.

How do I write query for the latter part?

select temp.product_id,temp.variation_ids,temp.variationinfo_id,vi.stock
(select p.product_id,group_concat(v.id) as variation_ids, v.variationinfo_id

 from ProductVariation p 
join Variation v on p.variation_id=v.id

group by p.product_id,v.variationinfo_id) temp

join VariationInfo vi on temp.variationinfo_id=vi.id 

Note: Code is not tested. Small syntactic error may exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM