简体   繁体   English

如何在 SQL 中加入 4 个表?

[英]How to join 4 tables in SQL?

I just started using SQL and I need some help.我刚开始使用 SQL,我需要一些帮助。 I have 4 tables in a database.我在数据库中有 4 个表。 All four are connected with each other.这四个都是相互连接的。 I need to find the amount of unique transactions but can't seem to find it.我需要找到唯一交易的数量,但似乎找不到。

Transactions交易

  • transaction_id pk transaction_id pk
  • name姓名

Partyinvolved参与方

  • transaction.id pk交易.id pk
  • partyinvolved.id参与方.id
  • type (buyer, seller)类型(买方,卖方)

PartyCompany派对公司

  • partyinvolved.id参与方.id
  • Partycompany.id派对公司.id

Companies公司

  • PartyCompany.id pk PartyCompany.id pk
  • sector部门

pk = primary key pk = 主键

The transaction is unique if the conditions are met.如果满足条件,则交易是唯一的。 I only need a certain sector out of Companies, this is condition1.我只需要公司中的某个部门,这是条件1。 Condition2 is a condition inside table Partyinvolved but we first need to execute condition1. Condition2 是 Partyinvolved 表中的一个条件,但我们首先需要执行 condition1。 I know the conditions but do not know where to put them.我知道条件,但不知道把它们放在哪里。

SELECT *
FROM group
INNER JOIN groupB ON groupB.group_id = group.id
INNER JOIN companies ON companies.id = groupB.company_id
WHERE condition1 AND condition2 ;

I want to output the amount of unique transactions with the name.我想 output 与名称的唯一交易量。

It is a bit unclear what you are asking as your table definitions look like your hinting at column meanings more than names such as partycompany.id you are probably meaning the column that stores the relationship to PartyCompany column Id ......有点不清楚你在问什么,因为你的表定义看起来像你对列含义的暗示,而不是诸如partycompany.id类的名称,你可能是指存储与PartyCompanyId关系的列......

Anyway, If I follow that logic and I look at your questions about wanting to know where to limit the recordsets during the join.无论如何,如果我遵循这个逻辑,我会看看你关于想知道在加入期间在哪里限制记录集的问题。 You could do it in Where clause because you are using an Inner Join and it wont mess you your results, but the same would not be true if you were to use an outer join .您可以在Where子句中执行此操作,因为您使用的是Inner Join并且它不会弄乱您的结果,但如果您要使用outer join则情况并非如此。 Plus for optimization it is typically best to add the limiter to the ON condition of the join.另外,为了优化,通常最好将限制器添加到连接的ON条件中。

I am also a bit lost as to what exactly you want eg a count of transactions or the actual transactions associated with a particular sector for instance.对于您到底想要什么,例如交易计数或与特定部门相关的实际交易,我也有点迷茫。 Anyway, either should be able to be derived from a basic query structure like:无论如何,任何一个都应该能够从基本查询结构中派生出来,例如:

SELECT
    t.*
FROM
    Companies co
    INNER JOIN PartyCompancy pco
    ON co.PartyCompanyId = pco.PartyCompanyId
    INNER JOIN PartyInvolved pinv
    ON pco.PartyInvolvedId = pinv.PartyInvolvedId
    AND pinv.[type] = 'buyer'
    INNER JOIN Transactions t
    ON ping.TransactionId = t.TransactionId
WHERE
    co.sector = 'some sector'

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

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