Correct Join for sending Daily Notification Emails (PHP, Mysql)
I'm building a daily notification email script.
I need to join 4 tables to the user table, and I need the user_email in every while ($user = mysql_fetch_array($result)){
statement.
I was able to get this to work with an outer join with 1 table, but I'm having trouble getting the syntax to perform the objective with a different table to join after the first table join runs out of results. I wan开发者_如何学Pythont the mysql query to grab the contents until the first join runs out (for each user), and then start displaying data for the second join query (all executing in a while loop). Is this possible, if so, what would be the syntax?
Existing Code:
$sql = "SELECT *
FROM users
OUTER JOIN contest_entries ON contest_entries.email = users.email ";
$result = mysql_query($sql) or die (mysql_error());
The second query I want to attach is getting all new contests.
$sql = "SELECT *
FROM contests";
So for each user, I would want to display every contest_entries
field that is applicable to them, and then every contests
field that is applicable to them.
Note: In order to save processing power/time, I will probably just store all contests in a string and then add them to each email later, but I want to use this an example to find the correct multiple joining technique.
$sql = "SELECT *
FROM users
LEFT JOIN contest_entries
ON contest_entries.email = users.email
JOIN contests
ON contests.id = contest_entries.contestid
ORDER BY users.email --- or whatever other order you need
, contest.id ";
You can then iterate in PHP over the result set which is already ordered (and grouped) by users and contests.
If you haven't (yet) any way to relate users
with contests
, I guess you are still designing your application and database structure. You can use this to show users related to all contests and then experiment applying conditions in the WHERE
clause.:
$sql = "SELECT *
FROM users
LEFT JOIN contest_entries
ON contest_entries.email = users.email
CROSS JOIN contests
WHERE ( contests.started >= NOW() - interval 3 day ) --- new contests
AND ( users.age <= contests.agelimit )
AND ( some other condition )
ORDER BY users.email --- or whatever other order you need
, contest.id " ;
精彩评论