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的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 双百双新产业项目是什么_投资380亿,广
- 下一篇: 浏览器 android x86,360浏
