dongman5539 2011-03-02 02:03
浏览 14
已采纳

mysql子查询问题

I'm scratching my head over a MySQL subquery. And it's only after scratching for more than a couple of hours that I post it here in SO. So here it is:

$query_1 = "SELECT * 
              FROM table_new
             WHERE table_new.NAME NOT IN ('text I know does not exist') ";

$query_2 = "SELECT *
              FROM table_new, 
                   table_old
             WHERE table_new.NAME = table_old.NAME ";

$query_3 = "SELECT * 
              FROM table_new
             WHERE table_new.NAME NOT IN (SELECT * 
                                            FROM table_new, 
                                                 table_old
                                            WHERE table_new.NAME = table_old.NAME) ";

Here's the problem:
$query_1 and $query_2 work. But when I combine them in $query_3, it doesn't work.

Any thoughts?

  • 写回答

1条回答 默认 最新

  • double0201 2011-03-02 02:07
    关注

    Use:

    SELECT * 
      FROM table_new
     WHERE table_new.NAME NOT IN (SELECT table_old.NAME
                                    FROM table_old)
    

    Standard SQL only allows one column to column comparison in an IN clause -- you can't use SELECT * in an IN clause because it's not clear which columns values would be compared against in the outer query. However, MySQL is the only one that supports tuples to my knowledge.

    There are other ways of writing the query to get equivalent results:

    SELECT x.* 
      FROM TABLE_NEW x
     WHERE NOT EXISTS (SELECT NULL
                         FROM TABLE_OLD x
                        WHERE y.NAME = x.NAME)
    

    ...or:

       SELECT x.* 
         FROM TABLE_NEW x
    LEFT JOIN TABLE_OLD y ON y.NAME = x.NAME
        WHERE y.column_in_table_old IS NULL
    

    Which of those performs best depends on if the columns compared are nullable or not. For more info, see this page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入