美文网首页
MySql根据不同条件查询同一个字段进行连接查询并显示为两个字段

MySql根据不同条件查询同一个字段进行连接查询并显示为两个字段

作者: 勿念及时雨 | 来源:发表于2021-03-11 11:18 被阅读0次

功能需求

在字典表(com_dictionary)中查询类型( type_code) 为"水果" 且 字典编码(dictionary_code) 的值含有“果”字,查询出dictionary_code并显示为fruit_name字段,查询类型( type_code) 为"蔬菜" 且 字典值(dictionary_value) 为 "1",查询出dictionary_code并显示为vegetable_name字段,用户购买商品表(user_goods)中的goodsId对应字典表中的id,请查询出用户名(user_name)为"小明"的用户在日期(create_date)为"2021-3-11"这天购买的上述条件下的水果和蔬菜名称。

具体实现

知识点

使用连接查询,JOIN...ON语法后面可以跟多个条件。

SQL实现

以user_goods表为主表,根据不同条件,对com_dictionary表进行左连接查询,因为这里涉及到同一个表同一个字段dictionary_code,但是要根据不同条件查询出对应的记录并且拆分为两个字段显示,所以要左连接两次,将其看作两个单独的表进行关联查询即可。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

相关文章

网友评论

      本文标题:MySql根据不同条件查询同一个字段进行连接查询并显示为两个字段

      本文链接:https://www.haomeiwen.com/subject/ixpnqltx.html