日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql多列 groupby,MySQL多表查询之GroupBy

發布時間:2024/9/27 数据库 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql多列 groupby,MySQL多表查询之GroupBy 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

需求:根據主鍵id查詢到該顧客最近的一次消費記錄

SQL代碼如下:

SELECT

cbi.id,

cbi.mob,

cbi.identity_card,

bcil.remark,

bcil.orders_no,

bcil.brand_no,

bcil.with_date,

bcil.score

FROM

customer_base_info cbi

LEFT JOIN(

SELECT

A.customer_id,

A.with_date,

A.remark,

A.orders_no,

A.brand_no,

A.score

FROM

brand_customer_integral_log A,

(

SELECT

customer_id,

MAX(with_date)max_with_date

FROM

brand_customer_integral_log

GROUP BY

customer_id

)B

WHERE

A.customer_id = B.customer_id

AND A.with_date = B.max_with_date

) bcil ON (bcil.customer_id = cbi.id)

WHERE

cbi.id = '2c914df34997e204014997e2fe4e0001'

用到的兩張表:customer_base_info表為顧客基本信息,brand_customer_integral_log顧客消費記錄表。

一個顧客對應多個消費記錄, 即一對N的。所以用customer_base_info去左連接。我第一反映也是和很多人一樣直接左連接brand_customer_integral_log然后取ORDER BY(消費時間),最后根據customer_id來GROUP BY。 但結果是不對的。

這是因為MySQL:

寫的順序:select ... from... where.... group by... having... order by..

執行順序:from... where...group by... having.... select ... order by...

在ORDER By之前結果就已經SELECT出來了, 所以這樣的思路得到的結果是錯誤的。

選用子查詢來解決這個問題:

SELECT

A.customer_id,

A.with_date,

A.remark,

A.orders_no,

A.brand_no,

A.score

FROM

brand_customer_integral_log A,

(

SELECT

customer_id,

MAX(with_date)max_with_date

FROM

brand_customer_integral_log

GROUP BY

customer_id

)B

WHERE

A.customer_id = B.customer_id

AND A.with_date = B.max_with_date

把brand_customer_integral_log內連接, 根據customer_id查詢出MAX(with_date)最近消費時間, 這樣得到的才是所要的該顧客最近消費記錄。

結果如下:

總結

以上是生活随笔為你收集整理的mysql多列 groupby,MySQL多表查询之GroupBy的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。