我有两张桌子,第一张桌子
+----+-------------------------------------------------+------------+
| id | pixel | date |
+----+-------------------------------------------------+------------+
| 2 | 7FB30~8BBEA~2B1FB~D5C54~205BD~05A28~9FAB6~F8D2A | 1417334510 |
| 3 | 7FB30~8BBEA~2B1FB~D5C54~205BD~05A28~9FAB6~F8D2A | 1417358993 |
| 4 | 7FB30~8BBEA~2B1FB~D5C54~205BD~05A28~9FAB6~F8D2A | 1417443262 |
+----+-------------------------------------------------+------------+
表二
+----+---------+--------+------------+
| id | lead_id | status | date |
+----+---------+--------+------------+
| 11 | 3 | 2 | 1417359373 |
| 10 | 2 | 2 | 1417357705 |
| 12 | 2 | 4 | 1417422929 |
| 13 | 4 | 2 | 1417443292 |
+----+---------+--------+------------+
我想在one.id上加入第一至第二表.lead_id和最新日期 如果2.status等于x
,则选择它所以结果看起来像这样
+--------+--------+-------------+------------+-----------+------------+
| one.id | two.id | two.lead_id | two.status | one.pixel | two.date |
+--------+--------+-------------+------------+-----------+------------+
| 3 | 11 | 3 | 2 | 7FB30... | 1417359373 |
| 2 | 12 | 2 | 4 | 7FB30... | 1417422929 |
| 4 | 13 | 4 | 2 | 7FB30... | 1417443292 |
+--------+--------+-------------+------------+-----------+------------+
谢谢。
答案 0 :(得分:0)
我不确定" 2.status等于x"与问题或结果有关。看起来你想要表2中或表1之后的第一条记录。
这个想法是使用相关子查询来获取table1中每行的id的行。然后加入其余的字段:
select t.id as one_id, t.two_id, t2.lead_id, t2.status, t.pixel, t2.date
from (select t1.*,
(select t2.id
from table2 t2
where t2.date >= t1.date
order by date
limit 1
) as two_id
from table1 t1
) t join
table2 t2
on t.two_id = t2.id;