chick3n Posted November 21, 2007 Share Posted November 21, 2007 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. Link to comment https://forums.phpfreaks.com/topic/78257-query-to-get-results-wether-other-results-exists-or-not/ Share on other sites More sharing options...
fenway Posted November 21, 2007 Share Posted November 21, 2007 You mean a UNION? You can't join tables that way. Link to comment https://forums.phpfreaks.com/topic/78257-query-to-get-results-wether-other-results-exists-or-not/#findComment-396015 Share on other sites More sharing options...
chick3n Posted November 21, 2007 Author Share Posted November 21, 2007 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? Link to comment https://forums.phpfreaks.com/topic/78257-query-to-get-results-wether-other-results-exists-or-not/#findComment-396042 Share on other sites More sharing options...
fenway Posted November 21, 2007 Share Posted November 21, 2007 Your examples aren't equivalent. Link to comment https://forums.phpfreaks.com/topic/78257-query-to-get-results-wether-other-results-exists-or-not/#findComment-396260 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.