0

How should I do query where

  • I have (table1) row which can have none or several rows referencing to it in other table
  • These referencing (table2) rows have colum1 that can be null or date

I would like to have all rows from table1 which have all rows column1 not as null or no rows at all, in table2.

Of course the basic sql goes like:

SELECT table1.* FROM table1 JOIN table2 ON table2.id = table1.table2_id

But what comes next?

1 Answer 1

1

You can count the occurences of null in your query like SUM(CASE WHEN table2.col IS NULL THEN 1 ELSE 0 END) AS nullcount, i assume table2.col is the one which has date of null in it

SELECT 
  table1.*,
  SUM(
    CASE
      WHEN table2.col IS NULL 
      THEN 1 
      ELSE 0 
    END
  ) AS nullcount 
FROM
  table1 
  JOIN table2 
    ON table2.id = table1.table2_id 
HAVING nullcount > 0 
Sign up to request clarification or add additional context in comments.

9 Comments

@AngularAddict see working fiddle there is difference between where and having
Ok. Thanks. But how can get also c_contact row with id=2 as it has no references in c_monitoring. Actually what I want is rows from c_contact that has no rows in c_cmonitoring or all c_monitoring ended rows are dates, not nulls. Updated fiddle: sqlfiddle.com/#!2/f7b17/4
@AngularAddict see second query i have added the one more condition in on clause and the row which has 0 null dates are there first query is just to show the data set
@AngularAddict try your query with exists fiddle Not in is also makes your query slow
@AngularAddict add these two indexes if you have not added already ALTER TABLE c_contact ADD INDEX test (securityid); ALTER TABLE c_monitoring ADD INDEX test1 (securityid);
|

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.