我正在使用MySql 5.6,并具有一个带有LEFT JOIN的选择查询,但我需要检索关联列email_nb
的最大值),但约束的范围不同。
让我们举个例子:让我说这只是一个仅有5行的例子,但是当我有成千上万行时它也可以工作...(我说这是因为查询中有LIMIT
子句)
表'query_results'
+-----------------------------+------------+--------------+
| query_result_id | query_id | author |
+-----------------------------+------------+--------------+
| 2 | 1 | john |
| 3 | 1 | eric |
| 7 | 3 | martha |
| 9 | 4 | john |
| 10 | 1 | john |
+-----------------------------+------------+--------------+
表'customers_emails'
+-------------------+-----------------+--------------+-----------+-------------+------------------------
| customer_email_id | query_result_id | customer_id | author | email_nb | days_since_sending
+-------------------+-----------------+--------------+-----------+-------------+------------------------
| 5 | 2 | 12 | john | 2 | 150
| 12 | 3 | 7 | eric | 4 | 90
| 27 | 3 | 12 | eric | 2 | 86
| 40 | 9 | 15 | john | 9 | 87
| 42 | 2 | 12 | john | 7 | 23
| 51 | 10 | 12 | john | 3 | 89
+-------------------+-----------------+--------------+-----------+-------------+-----------------------
注意:
您可以有一个query_result
,其中作者在customers_emails
中的任何一个中都根本没有出现在行中,因此我正在使用LEFT JOIN
。
您可以看到author
在设计上是重复的,因为每次与query_result_id
相关联时,它都在第一张表和第二张表上。请务必注意。
email_nb
是0到10之间的整数
有一个LIMIT
子句,因为我需要检索一定数量的记录
[今天,我的查询旨在通过一定数量的条件检索 我当前的查询query_results
。特异性是,我确保使用author
检索query_results,该查询不会出现在customer_email_id
较小的任何days_since_sending
中超过60天:这意味着我不仅要在此查询的记录中检查这些days_since_sending
,还要感谢子查询customers_emails
(请参见下文)。这是NOT IN
和customer_id = 12
query_id = 1
这是预期的输出:
SELECT qr.query_result_id, qr.author, FROM query_results qr LEFT JOIN customers_emails ce ON qr.author = ce.author WHERE qr.query_id = 1 AND qr.author IS NOT NULL AND qr.author NOT IN ( SELECT recipient FROM customers_emails WHERE ( customer_id = 12 AND ( days_since_sending >= 60) ) ) ) # we don't take by coincidence/bad luck 2 query results with the same author GROUP BY qr.author ORDER BY qr.query_result_id ASC LIMIT 20
我今天的挑战/困难:
+-----------------------------+------------+--------------+
| query_result_id | author | email_nb |
+-----------------------------+------------+--------------+
| 10 | john | 7 |
| 3 | eric | 2 |
+-----------------------------+------------+--------------+
email_nb
,而不是如果我们将所有邮件中的2
的最大值取为4
,则不是Eric的所有电子邮件的最大值]。但我们保持在email_nb
的范围内,因此author=eric
customer_id = 12
关联的email_nb = 2
是email_nb
,而不是query_result = 10
,可能是这种情况,因为7
是表3
]的最后一行。3
customers_emails
,email_nb
和2
之间进行选择,但我的接受程度最高,因此为7
(即使该电子邮件来自60天以上以前!!这非常重要,这也是我不知道怎么做的一部分:周长不同:今天我检索了过去60天未向3
发送电子邮件的所有query_results。 [7
子查询),但我需要在列中包含author
和NOT IN
发送到email_nb
的最大john
,即使它已发送超过60天,所以它们是不同的周长... Don真的不知道该怎么做...customer_id=12
子句(如query_id=1
)或同一个LIMIT和GROUP BY中找到最大值(email_nb):我需要检索WHERE
和days_since_sending >= 60
的email_nb
最大值,并通过customer_id=12
表上的所有记录!
query_id=1
这意味着我不想要此输出:
john
如何在MySQL 5.6中实现?
我使用的是MySql 5.6,并且具有一个带有LEFT JOIN的选择查询,但是我需要检索关联列email_nb的最大值),但是具有不同的“边界”约束。让我们举个例子:...
customers_emails