Ask a moderator simple questions

Source: Internet
Author: User
Table A table B
ID Value ID Value
20120101 120 20120101 10
20120201 100 20120304 5
20120301 90 20120401 6
20120401 72 20120501 7
20120501 45 20120601 16
20120601 75 20120701 80
20120701 60 20120901 15

Two tables. The same ID value is added and the output is looped by ID. How to write. Really ask for help Ah!


Reply to discussion (solution)

Select ID, sum (value)
(
SELECT * FROM A
UNION ALL
SELECT * FROM B
) T
Group by ID;

If the two tables above are the two records retrieved by my SQL statement. Items that need to be added by the same ID are not added. and loop output by ID

Do not know what you mean, the above statement tried it.

Well, it's OK to write like this. But I am now executing two SQL statements to get the above values and then loop the output. By ID Flashback causes the addition to not correspond. Use a while loop.
while ($date =mysql_fetch_array ($sql)) {
$aa =mysql_fetch_array ($query)
$BB =mysql_fetch_array ($querys)

echo $aa [1]+ $bb [1];

} So output because I $query $querys statements are flashbacks by time, and when the second result sets more data or the first less data, it causes no correspondence. Just adding a flashback is not accurate. Want to solve this.

Why take two times, which SQL I can use.

Two table links, with sub-query

1. Left connection
2. Adding fields
3.having Query


Your two SQL, can write one, and return the result set.
Select SUM (a.value+b.value), A.value,b.value
From A left join B on A.id=b.id GROUP by a.id

Your two SQL, can write one, and return the result set.
Select SUM (a.value+b.value), A.value,b.value
From A left join B on A.id=b.id GROUP by a.id
There are also different IDs to output,

Select SUM (a.value+b.value), A.value,b.value
From A left join B on A.id=b.id GROUP by a.id

You can try the union all a.b table.

  • 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.