我想在id列上连接两个表,其中id在table1中是唯一的,但在table2中重复或可能不存在。在table2中,我想使用第二列(日期)来选择最大日期,该日期小于与table1行中的日期对应的日期。我需要从表2中选择其他列。
我的查询是:
<span class="wpcf7-form-control-wrap list-tosafot1">
<span class="wpcf7-form-control wpcf7-checkbox" id="options1st">
<span class="wpcf7-list-item first">
<input type="checkbox" name="list-tosafot1[]" value="price-100" />
<span class="wpcf7-list-item-label">Checkbox1 - price 100</span>
</span>
<span class="wpcf7-list-item">
<input type="checkbox" name="list-tosafot1[]" value="price-200" />
<span class="wpcf7-list-item-label">Checkbox2 - price 200</span>
</span>
<span class="wpcf7-list-item">
<input type="checkbox" name="list-tosafot1[]" value="price-300" />
<span class="wpcf7-list-item-label">Checkbox3 - price 300</span>
</span>
<span class="wpcf7-list-item">
<input type="checkbox" name="list-tosafot1[]" value="price-400" />
<span class="wpcf7-list-item-label">Checkbox4 - price 400</span>
</span>
<span class="wpcf7-list-item last">
<input type="checkbox" name="list-tosafot1[]" value="price-500" />
<span class="wpcf7-list-item-label">Checkbox5 - price 500</span>
</span>
</span>
</span>
问题是您无法在SELECT * FROM `t1` LEFT JOIN
(SELECT `t2`.`other_column`, MAX(`t2`.`date`) FROM `t2` GROUP BY `t2`.`id` WHERE `t2`.`date`<`t1`.`date` )
ON `t1`.`id` = `t2`.`id`
子查询的WHERE子句中使用t1
变量。
答案 0 :(得分:2)
您可以使用 select 子句中的相关子查询执行所需操作:
SELECT t1.*
(SELECT MAX(t2.date)
FROM t2
WHERE t2.id = t1.id AND t2.date < t1.date
) as t2date
FROM t1 ;
答案 1 :(得分:2)
SELECT * FROM t1
INNER JOIN
(
SELECT id, MAX(t2.date) AS `date` FROM t2 GROUP BY id
) t3 ON (t3.id = t1.id AND t3.date < t1.date)
答案 2 :(得分:0)
原来,子查询是一个红色的鲱鱼,如果没有它,我可以做到这一切。
SELECT `t1`.*, `t2`.*, MAX(`t2`.`date`) FROM `t1`
LEFT JOIN `t2`
ON (`t1`.`id`=`t2`.`id` AND `t2`.`date`<`t1`.`date`)
GROUP BY `t1`.`id`