我正在尝试从3个表格中获取数据,这些表格是:“艺术家”,“销售”,“索赔”
所以我想尝试获取每个“艺术家”的收入(从“总销售”中获得),并且如果他们已经要求一些销售,这些数据保存在表“ claim”中
这是每个表的结构:
*Table Artist:
Artist_id
Artist_name
Artist_profile
*Table Sales :
Sales_id
Artist_name
Sales_amount
*Tables Claim :
Claim_id
Artist_name
Claim_amount
我尝试了一些查询,但没有获得我期望的某些值在“ Claim_amount”列中循环, 假设表“ sales”有多个数据,而表“ claim”还没有数据,因为没有索赔历史。
SELECT artist.member_id,artist.profile_pict, sales.artist_name,
SUM(sales.amount) AS total_sales ,claim.claim_amount
FROM sales,artist,claim
WHERE sales.artist_name OR claim.artist_name = artist.username
GROUP BY sales.artist_name
ORDER BY total_sales DESC
我希望输出类似于示例:
Artis_id | Artist_profile | Artist_name | Total_amount | Total_claim
1 Artist A My Artist 1 100 50
2 Artist B My Artist 2 200 null (because there is no history)
3 Artist C My Artist 3 300 150
答案 0 :(得分:0)
使用left join
SELECT a.member_id,a.profile_pict, a.artist_name,
SUM(sales.amount) AS total_sales ,sum(claim_amount) as total_claim
FROM artist a left join sales s on a.Artist_name=s.Artist_name
left join claim c on c.Artist_name= a.Artist_name
GROUP BY a.member_id,a.profile_pict, a.artist_name
ORDER BY total_sales DESC
注意:最好总是使用显式连接,而不是逗号分隔的连接
答案 1 :(得分:0)
使用外键ID
存在Artist_name,但名称可以相同。通过ID与每个表建立联系。
然后您可以使用左联接轻松获取数据