首页 文章

关于mysql中两个表的复杂SELECT逻辑

提问于
浏览
0

我有两个表具有以下架构

表1

field1 |域2

表2

field2 |字段3

我想做的是以下内容:

获取 field2 AND field3 FROM table2 IF THERE ARE NO table1.field2 = table2.field2 AND table1.field = 'x'

在演练中:

表1

field1 |域2

1 |某物

1 | somethingelse

2 |另一个

表2

field2 |字段3

还有一个|要得到

在这个例子中我想得到 'yetanother' and 'to_get' 因为table2中没有字段field2 = yetanother 而查询中我的'x'是1.这个问题是我将检索 2x times the information I want because there are two times the field1 = '1' in table1 . 因此,由于重复,我的查询将获得 yetanother, to_get; yetanother, to_get . 我尝试使用 DISTINCTLIMIT ,但这不起作用,因为它应用于table2中的字段,而不是table1中的字段 . 所以,如果我在table1中有3行 field1 = 1distinctlimit 将"erase"其中之一并检索两个 yetanother, to_get; yetanother, to_get . 如果我有10行,其中field1 = '1',它将检索9次 yetanother, to_get . 如果有一行"field1 = '1'"和"field2 = 'yetanother'",那么我希望查询不返回任何内容(因为field2是共同的) . 我怎样才能做到这一点?我不知道在这里弄错了什么,我忘记了...

2 回答

  • 0

    Try this homie

    SELECT DISTINCT *             /* select all */
    FROM table1 t1, table2 t2     /* from these 2 tables */
    WHERE t1.field2 <> t2.field2  /* where t1 field1 != t2  field1 */
    AND t1.field1 = 'x';          /* and t1.field 1 is X */
    

    如果它适合您,请告诉我 .

  • 0

    只需使用 not exists

    select t2.*
    from table2 t2
    where not exists (select 1
                      from table1 t1
                      where t1.field2 = t2.field2 and t1.field = 'x'
                     );
    

相关问题