简体   繁体   English

联接三个SQL表?

[英]JOINing Three SQL Tables?

I have a working SQL query, but I need to grab another piece of data from a third table in the query for ease of use, but have been unable to grab it. 我有一个正在运行的SQL查询,但是为了易于使用,我需要从查询的第三个表中获取另一条数据,但是一直无法获取它。

Every table is basically tied together by tenant_id 每个表基本上都由tenant_id绑在一起

(I apologize for the bad structure, I didn't create the DB) (对于不好的结构,我深表歉意,我没有创建数据库)

TABLE: tenant_statements 表格:tenant_statements

tenant_id balance property date tenant_id余额属性日期

TABLE: leases 表格:租赁

lease_id tenant_id property unit_number lease_id tenant_id属性unit_number

TABLE: tenants 表格:租户

tenant_id first_name last_name global_comment tenant_id first_name last_name global_comment

My current query: 我当前的查询:

SELECT * 
FROM tenant_statements t
INNER JOIN (
SELECT * 
FROM leases
GROUP BY tenant_id
ORDER BY lease_id
)l ON t.tenant_id = l.tenant_id
WHERE t.date = '$date'
AND t.property = '$property'
ORDER BY t.balance DESC

This give's me the appropriate response for joining the two tables: leases and tenant_statements . 这是给予我要加入两个表适当的响应: leasestenant_statements $date and $property are set via a PHP variable loop and used for presentation. $date$property通过PHP变量循环设置并用于演示。

What I am attempting to do is also grab tenants.global_comment and have it added each result. 我正在尝试做的是也抓住tenants.global_comment并将其添加到每个结果中。

the ideal output will be: 理想的输出将是:

tenant_statements t: t.balance, t.date tenant_statements t:t.balance,t.date

leases l: l.property, l.unit_number 租约l:l.property,l.unit_number

tenants x: x.first_name, x.last_name, x.global_comment 租户x:x.first_name,x.last_name,x.global_comment

All in one query. 一站式查询。

Can anyone point me in to the right direction? 谁能指出我正确的方向? Thank you! 谢谢!

How about something like 怎么样

SELECT * 
FROM    tenant_statements t INNER JOIN 
        (
            SELECT * 
            FROM leases
            GROUP BY tenant_id
            ORDER BY lease_id
        )l ON t.tenant_id = l.tenant_id INNER JOIN
        tenants ts  ON  t.tenant_id = ts.tenant_id
WHERE   t.date = '$date'
AND     t.property = '$property'
ORDER BY    t.balance DESC

Although each join specification joins only two tables, FROM clauses can contain multiple join specifications. 尽管每个联接规范仅联接两个表,但是FROM子句可以包含多个联接规范。 This allows many tables to be joined for a single query. 这样就可以将多个表合并为一个查询。

 SELECT  t.tenant_id,
t.balance,
l.unit_number,
l.property
x.first_name, x.last_name, x.global_comment


fROM  tenant_statements t
   INNER JOIN  leases l ON l.tenant_id = t .tenant_id
   INNER JOIN tenants x  on x.tenant_id = t.tenant_id

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

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