R
R
Rinsewind2016-06-12 00:51:31
MySQL
Rinsewind, 2016-06-12 00:51:31

How to correctly select data from two tables?

There are two tables of the following form:
A:

  • id
  • x
  • y

B:
  • a_id
  • z

It is necessary to select all data from table A and the sum of all Bz for A.id. If there are no records with the required a_id, select the sum as 0.
Query like:
select A.*, SUM(B.z) from A,B where A.id = B.a_id GROUP BY A.id;

Doesn't return rows from table A that don't have a match in table B.
How can this be dealt with?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sanan Yuzb, 2016-06-12
@Sanan07

Use LEFT JOIN

M
mark1yan, 2016-06-12
@mark1yan

Use a nested query
here you will find the necessary information, well, or join)

N
nozzy, 2016-06-13
@nozzy

select
 t1.id,
 t1.x,
 t1.y,
 ifnull(sum(t2.z),0) 
 from A t1
 left join B t2 on t2.a_id = t1.id
 group by t1.id,t1.x,t1.y

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question