2

我有两个表如下:

表格1:

ID Code Detail
1  45   Yes
2  46   No

和表 2:

Code Detail1 Detail2
45   No    23
22   Yes   34

是否可以选择所有FROM TABLE 2 where detail = YES 并且 TABLE 1 包含 Code 并说 Yes

即查询结果应该是

Code Detail Detail
45   No     23
22   Yes    34

谢谢。

4

2 回答 2

3

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)

虽然,我上面的查询似乎为您提供了正确的示例结果集,但我认为以下查询更好地满足您的条件:

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
于 2013-06-03T16:07:34.587 回答
1

我没有很好地理解您的问题,但这将创建您想要的结果表。

select table2.* from table2 left join table1 on table2.code = table1.code where table2.Detail1 = 'Yes' or table1.Detail = 'Yes'
于 2013-06-03T16:07:14.647 回答