【问题标题】:Mysql query select row id that is not in the other tableMysql查询选择不在其他表中的行ID
【发布时间】:2016-05-25 20:40:10
【问题描述】:

我必须表 'config_questions' 和 'user_question'。

'config_questions' 字段:

  • question_id
  • question_text

'user_question' 字段

  • question_id
  • user_id

mysql 结果(question_text 字段)必须是“config_questions”表中的一个问题,其中 question_id 和 user_id 不在“user_question”表中。

我从哪里开始?如何在一个查询中进行管理?

【问题讨论】:

    标签: php mysql row field


    【解决方案1】:

    我假设您正在为给定用户寻找一个新问题,因此您只希望返回一个问题。

    select min( question_text) from config_questions
     where question_id not in (select question_id 
                                 from user_question 
                                where user_id = 1);
    

    将为 user_id = 1 执行此操作。

    【讨论】:

      【解决方案2】:

      不使用

       select question_text  from config_questions 
       where question_id not in (select question_id from user_question);
      

      【讨论】:

        【解决方案3】:

        使用

        SELECT question_id, question_text 
        FROM config_questions
        WHERE question_id NOT IN (
            SELECT question_id 
            FROM user_question)
        

        开始一个子选择,为您提供来自 user_questions 的所有 question_id,并仅选择那些没有其中之一的问题(NOT IN 仅返回与以下模式不匹配的结果)。

        如果你真的只想要一个结果,你可以使用 SELECT TOP 1 question_id, question_text

        【讨论】:

        • 为什么 OP 应该“尝试”这个? 好的答案将始终解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,也是为了 SO 的未来访问者。跨度>
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-08
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多