Ask a MySQL query about the problem, send 100 points

Source: Internet
Author: User
Ask a MySQL query question, send 100 points
This post was last edited by Shandiandian on 2013-12-12 12:15:27

Table A table B
UID Mid cash UID Mid cash number
1 1 100 1 1 101 100
2 2 105 2 1 100 100
3 3 98 3 2 105 200
4 4 55 4 2 105 300
5 5 60 5 3 60 300
6 6 70 6 3 98 300

UID is auto-grow field mid and cash are associated fields

I want to count the sum of table B as follows, no match to table A shows 0, matches the mid and cash two fields. How can I write sql?? Table A as the base table
Results table
UID Mid cash number
1 1 100 100
2 2 105 500
3 3 98 300
4 4 55 0
5 5 60 0
6 6 70 0

Share to: more


------Solution--------------------
You are too naughty, and then you edited the post.
Look at this
Http://sqlfiddle.com/#!2/9847b/12
------Solution--------------------
Create temporary table A
Select 1 as UID, 1 as Mid, cash
Union select 2, 2, 105
Union Select 3, 3, 98
Union Select 4, 4, 55
Union Select 5, 5, 60
Union Select 6, 6, 70;

Create temporary table B
Select 1 as UID, 1 as Mid, 101 as cash, as number
Union select 2, 1, 100
Union Select 3, 2, 200
Union Select 4, 2, 300
Union Select 5, 3, 300
Union Select 6, 3, 98, 300;

Select Uid,mid, Cash, (select sum (number) from B where Mid=a.mid and Cash=a.cash) from A
1 1 100 100
2 2 105 500
3 3 98 300
4 4 55
5 5 60
6 6 70

Writing test data takes more than 10 times times more time than writing query instructions.

------Solution--------------------

Select A.uid, A.mid, A.cash, sum (b.number) from Testa as a left join Testb as B on a.mid=b.mid and a.cash = B.cash Group B Y A.mid, A.cash


The return result is
UID Mid cash sum (b.number)
11100100
22105500
3398300
4455
5560
6670
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.