mysql多表複雜業務查詢(如下),應該怎樣寫查詢語句?

來源:互聯網
上載者:User
需要查詢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吧

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.