简体   繁体   中英

SQL Query for data consolidation from two tables

Taking a customer table as example

CREATE TABLE customer (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  name VARCHAR(20));
CREATE TABLE payments (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  customer_id INT(11),
  month INT(2),
  year INT(4),
  amount INT(5),
  FOREIGN KEY fk_cust(customer_id)
  REFERENCES customer(id));

The payments table contains information about the month, year and amount of payment by the customer.

I have trouble writing a SELECT query. The result should contain all months of a particular year for all customers, if the customer hasn't made a payment for a particular month, the payment column should be NULL for that month.

SELECT * FROM customers c
LEFT JOIN payments p ON c.id = p.customer_id AND p.year = 2017

If I run the above query, I only get rows which have months with payments.

I apologize in advance for any mistakes(I'm new to MySQL and StackOverflow).

EDIT: The query should return entries for months where payments don't exist. For example, If a customer made payment only in June, the query should return entries for other months too with NULL value as payments.

It is actually the opposite join:

   Select * from payments p 
   left join customers c 
       on p.customer_id = c.id

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