简体   繁体   English

一次从两个表中检索数据,一个表引用另一个表

[英]Retrieving data from two tables at once with one table referencing the other

I have two table as follows: 我有两个表,如下所示:

TABLE 1: 表格1:

ID Code Detail
1  45   Yes
2  46   No

AND TABLE 2: 和表2:

Code Detail1 Detail2
45   No    23
22   Yes   34

Is it possible to select all FROM TABLE 2 where detail = YES AND where TABLE 1 contains Code and says Yes ? 是否可以从table 2中全部选择,其中detail = YES并且Table 1包含Code并说Yes

ie query result should be : 即查询结果应为

Code Detail Detail
45   No     23
22   Yes    34

Thanks. 谢谢。

SQL Fiddle: http://sqlfiddle.com/#!2/6f583/9 SQL小提琴: http ://sqlfiddle.com/#!2 / 6f583 / 9

SELECT
    Table2.Code,
    Table2.Detail1,
    Table2.Detail2
FROM
    Table1,
    Table2
WHERE
    Table1.Detail = "Yes" OR
    (Table2.Detail1 = "Yes" AND
    Table1.Code = Table2.Code)

Although, my above query seems to give you the correct resultset for the example, I think that the following query better satisfies your criteria: 尽管以上查询似乎为您提供了示例的正确结果集,但我认为以下查询可以更好地满足您的条件:

SQL Fiddle: http://sqlfiddle.com/#!2/6f583/12 SQL小提琴: http ://sqlfiddle.com/#!2/6f583/12

SELECT
    Table2.Code,
    Table2.Detail1,
    Table2.Detail2
FROM
    Table1,
    Table2
WHERE
    (Table1.Code = Table2.Code AND
    Table1.Detail = "Yes") OR
    Table2.Detail1 = "Yes"
GROUP BY
    Table1.ID

我不太清楚您的问题,但这将创建您想要的结果表。

select table2.* from table2 left join table1 on table2.code = table1.code where table2.Detail1 = 'Yes' or table1.Detail = 'Yes'

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

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