Jump to content

query to get results wether other results exists or not


chick3n

Recommended Posts

MySQL ver 5.0.45

 

I have 3 tables, 2 of them will always have data i want, 1 of them may not.

I need a query that will return the results of the 2 tables always even if the condition in the 3rd table doesnt find a result.

 

Example query that works but only works if all conditions are met.

SELECT COUNT(DISTINCT table1.id) as total, table2.image, table3.name FROM table1
JOIN table2 ON table2.id = $var
JOIN table3 ON table3.id = $var2
WHERE table1.name='{$varName}' AND table1.submited > '{$varTime}';

 

So whenever the where clause matches i get all the data i want. However i want a query that will return 0 for COUNT if no matches are found and will return the results from table2, and table3. table2 and table3 always use a static variable and are not dependent on table1's data at all.

I tried union and it will give me my results however all as 1 field

------

field1

------

0

data1

data2

 

So to get what i wanted i did this for now, but i dont know if its exactly efficient.

SELECT 
(SELECT COUNT(DISTINCT table1.id) FROM table1 WHERE table1.name='{$varName}' AND table1.submited > '{$varTime}') as field1,
(SELECT id FROM table2 WHERE table2.id = $var) as field2,
(SELECT id FROM table3 WHERE table3.id = $var2) as field3

 

This produces the results i am looking for

--------------------

field1 | field2 | field3

--------------------

0      | sss    | sss

 

Is that an efficient work around to what i was looking for?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.