简体   繁体   English

mySQL:从两个表中获取数据,并按具有唯一ID的Date分组

[英]mySQL: Get data from two tables with grouping by Date with unique ID

There are two Stackoverflow questions on how to group tables together by date and I can get it to work. 关于如何按日期将表分组在一起,有两个Stackoverflow问题,我可以使它工作。 My problem is I only want records that belong to a unique client ID IE Where client_id = x 我的问题是我只想要属于唯一客户端ID IE的记录,其中client_id = x

My tables are: 我的表是:

TABLE INVOICE
invoice_id
client_id
invoice_number
invoice_amount
invoice_date

TABLE PAYMENT
payment_id
invoice_id
payment_amount
payment_date

At the moment my mySQL statement reads through the whole database. 目前,我的mySQL语句将读取整个数据库。 How do I get all invoice and payment details just for one client? 如何仅为一个客户获取所有发票和付款明细? IE WHERE client_id = x IE WHERE client_id = x

My mySQL statement is: 我的mySQL语句是:

SELECT payment_id AS idno, payment_amount AS debit, NULL as credit, payment_date 
AS added_on FROM payment 
UNION ALL 
SELECT invoice_id AS idno, NULL, invoice_total AS credit, invoice_date AS added_on FROM invoice 
WHERE client_id = 24 
ORDER BY added_on 

Do I have to have the same amount of columns from each table? 每个表中的列数都必须相同吗? How do I identify from which table the data comes from? 如何确定数据来自哪个表?

SELECT * FROM invoice i
JOIN payment p ON p.invoice_id = i.invoice_id
WHERE i.client_id= 24

I don't really know how the UNION , but i do know that your 2 two queries need the same amount of columns, just like you did. 我真的不知道UNION ,但是我确实知道您的两个查询需要相同数量的列,就像您所做的一样。

I think the reason for your sql statement reading through the whole table is because your two tables are not joined, to do this you can do like @Sid-Hussain mentioned, by joining them in your first SELECT . 我认为您的sql语句读取整个表的原因是因为您的两个表未联接,为此,您可以像将@ Sid-Hussain提到的那样,通过将它们加入第一个SELECT You then just need to add WHERE client_id = 24 on the your first SELECT 然后,您只需要在第一个SELECT上添加WHERE client_id = 24

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM