功能需求
在字典表(com_dictionary)中查詢類型( type_code) 為"水果" 且 字典編碼(dictionary_code) 的值含有“果”字,查詢出dictionary_code并顯示為fruit_name字段,查詢類型( type_code) 為"蔬菜" 且 字典值(dictionary_value) 為 "1",查詢出dictionary_code并顯示為vegetable_name字段,用戶購買商品表(user_goods)中的goodsId對應(yīng)字典表中的id,請查詢出用戶名(user_name)為"小明"的用戶在日期(create_date)為"2021-3-11"這天購買的上述條件下的水果和蔬菜名稱。
具體實現(xiàn)
知識點
使用連接查詢,JOIN...ON語法后面可以跟多個條件。
SQL實現(xiàn)
以user_goods表為主表,根據(jù)不同條件,對com_dictionary表進行左連接查詢,因為這里涉及到同一個表同一個字段dictionary_code,但是要根據(jù)不同條件查詢出對應(yīng)的記錄并且拆分為兩個字段顯示,所以要左連接兩次,將其看作兩個單獨的表進行關(guān)聯(lián)查詢即可。SQL如下:
SELECT t1.user_name,t2.dictionary_code AS fruit_name,t3.dictionary_code AS vegetable_name,
t1.create_date FROM user_goods t1
LEFT JOIN com_dictionary t2 ON t1.goodsId= t2.id AND t2.type_code = '水果'
LEFT JOIN com_dictionary t3 ON t1.goodsId= t3.id AND t3.type_code = '蔬菜'
WHERE
t2.dictionary_code LIKE '%果%' AND t3.dictionary_value = '1'
AND t1.create_date = '2021-3-11'
order by t1.create_date desc