需要查詢A、B兩張表:
表A table_a:涉及到兩個欄位 a_id , a_date
| a_id | a_date | ... | ... || :-------- | --------: | :--: | :--: || 1 | 2014-03-12 | ... | ... || 2 | 2014-03-15 | ... | ... || 3 | 2013-08-06 | ... | ... || 4 | 2013-10-18 | ... | ... || 5 | 2012-04-15 | ... | ... || 6 | 2012-06-22 | ... | ... || ... | ... | ... | ... |
表B table_b:涉及到兩個欄位 b_id , b_category
| b_id | b_category | ... | ... || :-------- | ----------: | :--: | :--: || 1 | tom | ... | ... || 2 | jerry | ... | ... || 3 | tom | ... | ... || 4 | jerry | ... | ... || 5 | tom | ... | ... || 6 | tom | ... | ... || ... | ... | ... | ... |
需求:
1.從 table_b 查詢欄位名 b_category 等於 tom 的欄位 b_id 的值
2.將查得得值關聯到 table_a 查詢該 a_id 對應的 a_date 的值
3.對 a_date 截取前4位(年份),然後去重,並且按照倒序排列,輸出。
回複內容:
需要查詢A、B兩張表:
表A table_a:涉及到兩個欄位 a_id , a_date
| a_id | a_date | ... | ... || :-------- | --------: | :--: | :--: || 1 | 2014-03-12 | ... | ... || 2 | 2014-03-15 | ... | ... || 3 | 2013-08-06 | ... | ... || 4 | 2013-10-18 | ... | ... || 5 | 2012-04-15 | ... | ... || 6 | 2012-06-22 | ... | ... || ... | ... | ... | ... |
表B table_b:涉及到兩個欄位 b_id , b_category
| b_id | b_category | ... | ... || :-------- | ----------: | :--: | :--: || 1 | tom | ... | ... || 2 | jerry | ... | ... || 3 | tom | ... | ... || 4 | jerry | ... | ... || 5 | tom | ... | ... || 6 | tom | ... | ... || ... | ... | ... | ... |
需求:
1.從 table_b 查詢欄位名 b_category 等於 tom 的欄位 b_id 的值
2.將查得得值關聯到 table_a 查詢該 a_id 對應的 a_date 的值
3.對 a_date 截取前4位(年份),然後去重,並且按照倒序排列,輸出。
select distinct substr(a_date,1,4) result_datefrom table_a inner join table_b on a_id = b_idwhere b_category = "tom"order by result_date desc
應該用join吧