zoukankan      html  css  js  c++  java
  • Mysql中的GROUP_CONCAT使用

     SELECT
        res.ITRId Id,
        res.ITRResourceName ResourceName,
        res.ITRSupplierName SupplierName,
        res.ITRDeptCityName DeptCityName,
        res.ITRDeptAirportName DeptAirportName,
        res.ITRDataFlag DataFlag,
        res.ITRDeptCityId,
        res.ITRSupplierId,
        res.ITRTcManagerId,
        bus.ITFDestCityName DestCityName,
        bus.ITFDestAirportName DestAirportName,
        city.ITCTransPortCityName
        -- (select GROUP_CONCAT(city.ITCTransPortCityName separator  ',' ) TransportCityName from SGRInternationalTransportCity city where   city.ITCTransportId = res.ITRId) as TransportCityName
        FROM SGRInternationalTransportResources res
        left JOIN SGRInternationalTransportFlightResource bus ON res.ITRId = bus.ITFTransportId
        left JOIN SGRInternationalTransportCity city ON city.ITCTransportId = res.ITRId
        where res.ITRResourceType =2

    执行的结果如下:

    表联合查询后ID相同的存在多条记录;其他字段值均一样仅ITCTransPortCityName字段值不同;

    使用GROUP_CONCAT 优化后:

     SELECT
        res.ITRId Id,
        res.ITRResourceName ResourceName,
        res.ITRSupplierName SupplierName,
        res.ITRDeptCityName DeptCityName,
        res.ITRDeptAirportName DeptAirportName,
        res.ITRDataFlag DataFlag,
        res.ITRDeptCityId,
        res.ITRSupplierId,
        res.ITRTcManagerId,
        bus.ITFDestCityName DestCityName,
        bus.ITFDestAirportName DestAirportName,
        (select GROUP_CONCAT(city.ITCTransPortCityName separator  ',' ) TransportCityName from SGRInternationalTransportCity city where   city.ITCTransportId = res.ITRId) as TransportCityName
        FROM SGRInternationalTransportResources res
        left JOIN SGRInternationalTransportFlightResource bus ON res.ITRId = bus.ITFTransportId
        left JOIN SGRInternationalTransportCity city ON city.ITCTransportId = res.ITRId
        where res.ITRResourceType =2

    已经初步得到我们想要的结果了;可结果集还是三条记录,列表呈现依然存在问题...进一步优化如下:

    去除:

        left JOIN SGRInternationalTransportCity city ON city.ITCTransportId = res.ITRId

    得到结果如下:

    如果需要对 ITCTransPortCityName 这个字段进行查询该如何处理?用 like 么?使用 exists 进行处理

     and exists (select 1 from SGRInternationalTransportCity city where res.ITRId = city.ITCTransportId and city.ITCTransPortCityId=226 )    

    已成功筛选 城市ID为 226 的城市

  • 相关阅读:
    java时间戳与Date相互转换、日期格式化、给日期加上指定时长、判断两时间点是否为同一天
    notepad++去掉红色波浪线
    发生异常Address already in use: bind
    SecureCRT背景颜色
    linux查看实时日志命令
    idel上传代码到github时遇到的Push rejected: Push to origin/master was rejected
    git解决error: The following untracked working tree files would be overwritten by checkout
    使用SecureCRT工具上传、下载文件的两种方法
    Windows下Zookeeper启动zkServer.cmd闪退问题的解决方案
    Maven的Snapshot版本与Release版本
  • 原文地址:https://www.cnblogs.com/zhangruiBlog/p/8421417.html
Copyright © 2011-2022 走看看