本文介紹了MySQL連接表基于主表中的MAX(日期)和帶限制的連接表中的MAX(Id)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
如果標(biāo)題沒(méi)有任何意義,下面是我需要在堅(jiān)果殼中做的事情。我需要在主表中”by date”選擇最近的X個(gè)記錄量,然后通過(guò)在連接表中”by id”選擇最近的記錄來(lái)連接屬于這些記錄的數(shù)據(jù)。
以下是一些示例輸出..
表:LEAD_UNIQUE(此表中只有唯一SSN)
+-----------+--------------+ | ssn | created_date | +-----------+--------------+ | 111111111 | 2015-03-01 | | 999999999 | 2015-03-03 | | 555555555 | 2015-02-08 | +-----------+--------------+
表:Lead_Data
+----+-----------+-------+----------------+-------------+-------+-------+ | id | ssn | name | address | city | state | zip | +----+-----------+-------+----------------+-------------+-------+-------+ | 1 | 111111111 | Bob1 | 1234 Test Ln | Mound | CA | 55555 | | 2 | 111111111 | Bob2 | 1234 Test Ln | Mound | CA | 55555 | | 3 | 999999999 | Jane1 | 5432 Lola Blvd | Patton | NJ | 33333 | | 4 | 999999999 | Jane2 | 5432 Lola Blvd | Patton | NJ | 33333 | | 5 | 555555555 | Jack1 | 832 92nd Ave N | Bright View | AL | 88888 | | 6 | 999999999 | Jane3 | 5432 Lola Blvd | Patton | NJ | 33333 | +----+-----------+-------+----------------+-------------+-------+-------+
所需輸出(可以是asc/desc日期列,無(wú)關(guān)緊要)
+--------------+-----------+-------+ | created_date | ssn | name | +--------------+-----------+-------+ | 2015-03-03 | 999999999 | Jane3 | | 2015-03-01 | 111111111 | Bob2 | | 2015-02-08 | 555555555 | Jack1 | +--------------+-----------+-------+
所需輸出(限制2)
+--------------+-----------+-------+ | created_date | ssn | name | +--------------+-----------+-------+ | 2015-03-03 | 999999999 | Jane3 | | 2015-03-01 | 111111111 | Bob2 | +--------------+-----------+-------+
查詢可能如下所示,但我也可能走錯(cuò)了路,因?yàn)槲以谶@里請(qǐng)求幫助,但運(yùn)氣不佳。
SELECT lead_unique.created_date, lead_unique.ssn, lead_data.name FROM lead_unique JOIN ( SELECT ... FROM lead_data ... ) lead_data ... ... LIMIT 2
我以前只用過(guò)一次堆棧溢出,所以如果還有什么我可以添加的,請(qǐng)讓我知道!謝謝!!
推薦答案
我傾向于對(duì)數(shù)據(jù)片段使用相關(guān)子查詢–您的問(wèn)題只提到一列:
select u.created_date, u.ssn,
(select d.name
from lead_data d
where d.ssn = u.ssn
order by d.id desc
limit 1
) as name
from lead_unique u
order by u.created_date desc
limit 2;
實(shí)際上,出于性能原因,我會(huì)將唯一組件放入子查詢中:
select u.created_date, u.ssn,
(select d.name
from lead_data d
where d.ssn = u.ssn
order by d.id desc
limit 1
) as name
from (select u.*
from lead_unique u
order by u.created_date desc
limit 2
) u;
編輯:
即使有多個(gè)列,性能最好的方法可能仍然是使用子查詢:
select created_date, ssn, d.*
from (select u.created_date, u.ssn,
(select d.id
from lead_data d
where d.ssn = u.ssn
order by d.id desc
limit 1
) as id
from (select u.*
from lead_unique u
order by u.created_date desc
limit 2
) u
) u join
lead_data d
on u.id = d.id;
順便說(shuō)一句,如果性能有問(wèn)題,您需要以下索引:lead_unique(created_date)
和lead_data(id)
。使用這兩個(gè)索引應(yīng)該會(huì)相當(dāng)快。
這篇關(guān)于MySQL連接表基于主表中的MAX(日期)和帶限制的連接表中的MAX(Id)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,