这是我的表结构:
users:
id | email
emails:
id | subject | body
user_emails:
user_id | email_id
这是非常简单的设计。但是,我需要为user_emails中没有关联的所有users.id选择第一个(最低的)emails.id。
举例说明:
users:
id | email
1 | email@domain.com
2 | test@lol.com
3 | user@test.com
emails:
id | subject | body
1 | sub1 | body1
2 | sub2 | body2
user_emails:
user_id | email_id
1 | 1
1 | 2
2 | 1
如数据所示:
我将在PHP中执行此操作,因此如果不能单独使用mySQL,那么任何逻辑都应该用PHP编写。
提前致谢
编辑:我应该提一下,会有成千上万的用户ID和数百个电子邮件ID。发送所有这些电子邮件的脚本将每天运行一次。所以,这应该尽可能优化。
答案 0 :(得分:2)
可以尝试下面的内容:
SELECT * from users u
LEFT JOIN users_emails e ON u.id=e.user_id
LEFT OUTER JOIN emails m on m.id=1
WHERE e.user_id is NULL
如果上述查询中电子邮件中的ID不必为1,请使用以下内容。
SELECT * from users u
LEFT JOIN users_emails e ON u.id=e.user_id
LEFT OUTER join emails m on m.id=(SELECT id from emails order by id limit 1)
WHERE e.user_id is NULL
答案 1 :(得分:0)
我想到了一个更简单的解决方案。我在用户表中添加了一个lastSent列。
// Load all emails into an array. Use the id as the key.
$sql = "SELECT * FROM emails";
$query = mysql_query( $sql );
while( $row = mysql_fetch_assoc( $query ) ) {
$emails[ $row['id'] ] = $row;
}
// Load all users into an array.
$sql = "SELECT id, email, lastSent FROM users";
$query = mysql_query( $sql );
while( $row = mysql_fetch_assoc( $query ) ) {
$users = $row;
}
// Loop through each user and send next email from the list based on lastSent value.
foreach ( $users as $user ) {
$id = $user['lastSent'] + 1;
$email = $user['email'];
$subject = $emails[$id]['subject'];
$body = $emails[$id]['body'];
$send = mail($email, $subject, $body);
if ( $send ) {
// Update lastSent value.
$sql = "UPDATE users SET lastSent='$id' WHERE id='" . $user['id'] . "'";
mysql_query( $sql );
}
}
答案 2 :(得分:0)
尝试使用以下查询
选择t.id,min(t.q_id)from(SELECT u.id,e.id as q_id FROM users u CROSS JOIN emails e)as t where(t.id,t.q_id)not in(select *来自user_emails)分组由t.id