简体   繁体   English

MySQL中的一对多查询

[英]One-to-many Query in MySQL

What's the best way to query one-to-many in MySQL? 在MySQL中查询一对多的最佳方法是什么? This is a simplified version of the database I am working on (if anything doesn't look right tell me): 这是我正在处理的数据库的简化版本(如果有什么不正确的告诉我):

CREATE TABLE Tenant(  
    tenant_id int NOT NULL,  
    first_name varchar(20),  
    last_name varchar(20),  
    PRIMARY KEY (tenant_id)  
);

CREATE TABLE Rent(  
    tenant_id int NOT NULL,
    month enum('JAN', 'FEB', ...),   
    date_paid date NOT NULL,  
    amount_paid int NOT NULL,  
    FOREIGN KEY (tenant_id) REFERENCES Tenant(tenant_id)  
);  

(The reason that there is month and date_paid in the Rent table is because the tenant does not necessarily pay the rent all at once). (Rent表中有month和date_paid的原因是因为租户不一定全部支付租金)。 What I want the tenant's name to appear once which would just be a Left Join, but I want all the amount paid in a particular month listed as columns for each tenant, I am not sure how to go about that. 我希望租户的名字出现一次只是一个左连接,但我希望在特定月份支付的所有金额列为每个租户的列,我不知道如何去做。 I am not really sure how to do that since your are dealing with an unknown amount of columns, haven't touched that yet in MySQL. 我不确定如何做到这一点,因为你正在处理未知数量的列,还没有触及MySQL中的那些。 Or is there a better strategy? 还是有更好的策略? Also, how would I go about creating my own variable like MONTH-YEAR (I don't think that exists as a native variable in MySQL). 另外,我将如何创建自己的变量,如MONTH-YEAR(我不认为它作为MySQL中的本机变量存在)。 Thank you! 谢谢!

Edit: Just to simplify it further I am using this format: 编辑:为了进一步简化它我使用这种格式:

create table rent(
tenant_id int not null,
year year,
amount_paid int,
foreign key (tenant_id) references tenant(tenant_id)
);

If I understand what duffymo said below I should use group by (I know I am misunderstanding somewhere because it only shows the first example for each year): 如果我理解duffymo在下面说的话我应该使用group by(我知道我在某处误解,因为它只显示了每年的第一个例子):
SELECT Tenant.first_name, Rent.year, Rent.amount_paid
FROM Tenant
LEFT JOIN Rent
ON Tenant.tenant_id = Rent.tenant_id
GROUP BY year;

This is what I want the query to look like, the number under each year is the amount paid (I actually just realized it's a little bit more complex than what I how explained): 这就是我想要查询的样子,每年下面的数字是支付的金额(我实际上只是意识到它比我解释的要复杂一点):

first_name 2009 2008 2007 first_name 2009 2008 2007
John 500 500 NULL 约翰500 500 NULL
Ann 1000 NULL NULL 安1000 NULL NULL
Bob NULL 700 700 Bob NULL 700 700

If you have MONTH and YEAR columns, you can do a GROUP BY to select amount paid broken out as you'd wish. 如果您有MONTH和YEAR列,则可以执行GROUP BY以根据需要选择已支付的金额。 If you have a PAID_DATE column, one way to do this would be to have a BEFORE INSERT trigger that runs when the PAID_DATE is set. 如果您有PAID_DATE列,则执行此操作的一种方法是在设置PAID_DATE时运行BEFORE INSERT触发器。 That way users don't have to enter values, and data integrity can be guaranteed. 这样,用户无需输入值,并且可以保证数据完整性。

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

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