简体   繁体   English

查询数据取决于其他表中的数据

[英]Query data depends on data from other table

I'm trying to get data from a table which is only related through two different tables. 我试图从仅通过两个不同的表相关的表中获取数据。 For example, I have information "dataA" and need to get information "dataD". 例如,我有信息“ dataA”,并且需要获取信息“ dataD”。

表数据关系

How do I write a query to display dataA and dataD as they relate? 如何编写查询以显示相关的dataA和dataD? I don't want to display all instances of dataD, just the ones that related to dataB and then to dataA. 我不想显示dataD的所有实例,仅显示与dataB然后与dataA相关的实例。 I'm sorry if this doesn't make enough sense. 很抱歉,如果这样做没有足够的道理。

You'll use JOINs to do this. 您将使用JOIN执行此操作。 Specifically, in this case, a LEFT OUTER JOIN is your best bet. 特别是在这种情况下,最好的选择是左外联接。 Something like: 就像是:

SELECT
    Table1.dataA,
    Table3.dataD
FROM
    Table1
    LEFT OUTER JOIN Table2 ON Table1.dataB = Table2.dataB
    LEFT OUTER JOIN Table3 ON Table2.dataC = Table3.dataC

Working on the assumption that the "data" entries you put under each table name represent columns in the table, this is fairly simple: 假设您在每个表名称下放置的“数据”条目表示表中的列,这很简单:

select dataA
  ,    dataD
from   Table1 t1
    join Table2 t2
         on t1.dataB = t2.dataB
    join Table3 t3
         on T2.dataC = t3.dataC

If you need all the dataA regardless of whether there's a matching dataD (or other intervening column) you would change where I wrote 'join' to 'left join' . 如果你需要的所有dataA而不管是否有匹配的dataD (或其它中间列),你会改变,我写了'join''left join'

And your question makes plenty of sense. 您的问题很有道理。 :) I was just a little unclear from the diagram what you had in mind. :)从图中我只是不清楚您的想法。

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

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