I have a query that returns some information I need in another query. I can parse the information and send it to a new query, but off the top of my head, that seems to be innefficient. Also, I'd have to order the data properly so I could line everything up when I display it. I was wondering if there's a better way to do it.
Here's my original query:
"SELECT b.id, b.bar_name
FROM barlist b, userdestinations ud
WHERE (b.id = ud.first_bar OR b.id = ud.second_bar OR b.id = ud.third_bar)
AND ud.id = '$userid' AND ud.date = '$current_date' AND b.id != 0";
I have a table, barlist, with fields 'id' and 'bar_name' along with some other stuff that doesn't really matter. The other table is userdestinations, with fields 'id', 'first_bar', 'second_bar', 'third_bar', and 'date'. The bars in userdestinations are 'id' fields from the barlist table, and the 'date' is represented as php's date("Ymd") or 20080130, for example. This query returns the 'id' and 'bar_name' of each bar a user plans on visiting on the specified date (b.id != 0 is used to throw out my fake bar in case the user only picked a 'first_bar').
So basically, after running that query, I have the 'id' field for up to 3 bars. My goal (and the reason for this post), is to use those id's to get the count of every user who might be going to each of those bars on the given night. If we knew those 3 bars had the 'id's 4, 7, and 12, then it's a quick fix to change the last query and get the desired results (I think), but I'm looking for a better way than running two queries. Here's the query that will get my results with those numbers:
"SELECT b.id, b.bar_name, count(b.id)
FROM barlist b, userdestinations ud
WHERE (b.id = ud.first_bar OR b.id = ud.second_bar OR b.id = ud.third_bar)
AND ud.date = '$current_date' AND b.id IN (4,7,12)";
All I did was remove where it specified the $userid and added the "b.id IN (4,7,12)" part. I can use implode to get (4,7,12) if I need to, but I feel like I'm missing something that could make this easier and combine them into one query. I really don't want to run two queries if I don't have to. I think it's better to do it in one query for performance reasons (although I admit I don't know too much about the performance side of queries), but I also don't want to have to add the extra code to sync the two queries up when I display them. Does anyone know how to combine them?
Sorry for the long post, but if anyone has any suggestions, they'd be greatly appreciated. If I left out any information you might need, let me know.