Jump to content

query to get results wether other results exists or not


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?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.