views:

91

answers:

4

How can I prevent inner SELECT from returning NULL (when matches no rows) and force query to fail.

INSERT INTO tt (t1_id, t2_id) VALUES (
  (SELECT id FROM t1 WHERE ...),
  (SELECT id FROM t2 WHERE ...)
);

Side question: is there better way form this query (t1_id, t2_id are foreign keys, but might be NULL) ?

+3  A: 
INSERT INTO tt (t1_id, t2_id) VALUES (
  (SELECT id FROM t1 WHERE ...),
  (SELECT id FROM t2 WHERE ...)
)
WHERE EXISTS (SELECT id FROM t1 WHERE ...)
AND (SELECT id FROM t2 WHERE ...)

It may seem awkward and redundant but any SQL executor worth its salt won't execute each part twice.

Alternatively if t1 and t2 are related somehow:

INSERT INTO tt (t1_id, t2_id)
SELECT t1.id, t2.id
FROM t1
JOIN t2 ON ...
WHERE ...
cletus
No, any decent SQL executor will NOT execute the SELECTs twice.
cletus
They don't have to be related. SimonJ gave valid answer.
LukLed
+5  A: 

How about something like:

INSERT INTO tt (t1_id, t2_id)
SELECT t1.id, t2.id FROM t1, t2 WHERE ...

Just make sure the SELECT returns exactly what you want to INSERT - so if it's possible for t1.id and t2.id to be NULL then include the relevant clause in your WHERE condition (... AND t1.id IS NOT NULL AND t2.id IS NOT NULL ...).

You may also prefer to use SELECT DISTINCT if there's a chance of duplicate rows appearing.

Edit: If you need 2 IDs from different rows of the same table:

SELECT t1.id, t2.id FROM some_table AS t1, some_table AS t2
WHERE ...
SimonJ
That's certainly an improvement. but what about NULL problem? I don't want to insert the NULL.
Łukasz Lew
@Łukasz Lew: If one of where conditions returns no rows, the whole query returns no rows and there are no rows inserted.
LukLed
Updated, thanks. Also see note about duplicate rows - I'm not sure how relevant it is as we can't see your real query :)
SimonJ
and what would be the syntax if t1 and t2 is the same table? (I need 2 different id's from it)
Łukasz Lew
Updated for 2 IDs from different rows - I think that's what you mean?
SimonJ
A: 
P Sharma
A: 
INSERT INTO tt (t1_id, t2_id) VALUES (
  IFNULL((SELECT id FROM t1 WHERE ...), 0),
  IFNULL((SELECT id FROM t2 WHERE ...), 0)
);

0 is the value you want to return if SELECT returns NULL

ssg