简体   繁体   中英

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

I have two table as follows:

TABLE 1:

ID Code Detail
1  45   Yes
2  46   No

AND TABLE 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 ?

ie query result should be :

Code Detail Detail
45   No     23
22   Yes    34

Thanks.

SQL Fiddle: 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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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