0

I have a following table in my project

+----+--------+-----------+-----------+
| id | old_id | op_status | tr_status |
+----+--------+-----------+-----------+
|  1 |        | issue     | Approved  |
|  2 |        | issue     | Approved  |
|  3 |        | issue     | Approved  |
|  4 |      1 | issue     | Issued    |
|  5 |      3 | issue     | Issued    |
+----+--------+-----------+-----------+

I want to select records WHERE tr_status='Approved' and NOT IN id in the old_row_id. In this example no need to select id(s) 1 and 3 that are in old_row_id as the following result.

+----+--------+-----------+-----------+
| id | old_id | op_status | tr_status |
+----+--------+-----------+-----------+
|  2 |        | issue     | Approved  |
+----+--------+-----------+-----------+

I used the following query.

SELECT id, old_row_id, op_status, tr_status FROM table WHERE id NOT IN (old_row_id).

But outs the following result.

+----+--------+-----------+-----------+
| id | old_id | op_status | tr_status |
+----+--------+-----------+-----------+
|  1 |        | issue     | Approved  |
|  2 |        | issue     | Approved  |
|  3 |        | issue     | Approved  |
+----+--------+-----------+-----------+

What may be wrong with me ? can anyone help me ?

1
  • See about joins Commented Jul 9, 2020 at 17:06

4 Answers 4

2

I would phrase your query using exists logic:

SELECT t1.id, t1.old_id, t1.op_status, t1.tr_status
FROM yourTable t1
WHERE
    t1.tr_status = 'Approved' AND
    NOT EXISTS (SELECT 1 FROM yourTable t2 WHERE t2.old_id = t1.id);

screen capture from demo link below

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

Try doing something like this:

SELECT id, old_id, op_status, tr_status 
FROM table 
WHERE id NOT IN (SELECT DISTINCT old_id FROM table)
AND tr_status = 'Approved'

Comments

1

You will want to left join the table to itself on the old ID, then eliminate the records where there is a match.

For example:

SELECT A.id, A.old_row_id, A.op_status, A.tr_status 
FROM table A
LEFT JOIN table B ON A.id = B.old_row_id
WHERE B.id IS NULL
AND A.tr_status = 'Approved';

Comments

-1

In they way you've tried to solve it, you're matching the old_id with the value of the row itself. You must derivate the table to create a cartesian product:

SELECT id, old_id, op_status, tr_status 
FROM table 
WHERE id NOT IN (SELECT IFNULL(old_id, 0) FROM table)
AND tr_status = 'Approved'

Also IFNULL to also include those record in the subquery, otherwise can't be compared with null

1 Comment

No idea who downvotes this answer, but the accepted answer so far does not work if old_id contains NULL since NULL does not matches with NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.