How to get records that match value or exist in another table?

前端 未结 3 1524
误落风尘
误落风尘 2021-01-29 07:44

I am trying to figure out how to get all tasks in this case that two of the fields equal a certain value or they exist in the other table?

Here is the query:

<         


        
相关标签:
3条回答
  • 2021-01-29 08:09

    Have you tried using a join?

    SELECT TASKS.task_id, 
           TASKS.task_title, 
           TASKS.task_description, 
           TASKS.task_assigned_name, 
           TASKS.task_assigned_phone_number, 
           TASKS.task_due_date_time, 
           TASKS.task_category
    FROM TASKS
    JOIN WATCHERS on WATCHERS.task_id = TASK.task_id
    WHERE TASKS.task_complete = 1 AND 
      (TASKS.task_creator_id = ? OR 
       TASKS.task_assigned_user_id = ? OR
       WATCHERS.watcher_user_id = ?);
    

    I'm not sure if that's the logic you are looking for.

    besides the extra where in your query, looks like you may have an extra closed parenthesis.

    0 讨论(0)
  • 2021-01-29 08:12

    You seem to have an error in your syntax. You have too many WHEREs:

       SELECT t.task_id, t.task_title, t.task_description, t.task_assigned_name, t.task_assigned_phone_number, t.task_due_date_time, t.task_category
        FROM TASKS t
        WHERE t.task_complete = 1 AND 
              (t.task_creator_id = ? OR 
               t.task_assigned_user_id = ? OR
               EXISTS (SELECT 1  -- the return value is immaterial
                       FROM WATCHERS w
                       WHERE w.task_id = t.task_id AND
                             w.watcher_user_id = ?
                      )
             );
    

    The WHERE before EXISTS is not appropriate.

    Your query should be returning an error. Be sure to check for errors!

    0 讨论(0)
  • 2021-01-29 08:13

    This sql matches the result set you posted in your duplicate post that has sample data and result:

    SELECT t.task_id, t.task_complete, t.task_creator_id, t.task_assigned_user_Id
    FROM tasks t
    WHERE t.task_complete = 1 AND
          (
          t.task_creator_id = 8
          OR t.task_assigned_user_id = 8
          OR EXISTS
              (
              SELECT w.task_id
              FROM watchers w
              WHERE w.task_id = t.task_id
              AND w.watcher_user_id = 8
              )
          )
    
    0 讨论(0)
提交回复
热议问题