mysql多个leftjoin连接查询⽤法分析
本⽂实例讲述了mysql多个left join连接查询⽤法。分享给⼤家供⼤家参考,具体如下:
mysql查询时需要连接多个表时,⽐如查询订单的商品表,需要查询商品的其他信息,其他信息不在订单的商品表,需要连接其他库的表,但是连接的条件基本都是商品ID就可以了,先给⼀个错误语句(查询之间的嵌套,效率很低):
SELECT
A.wid,
A.work_name,
A.supply_price,
A.sell_price,
A.sell_profit,
A.sell_percent,
A.classify,
B.gb_name
FROM
(
SELECT
A.sub_order_id AS order_id,
A.photo_id AS wid,
A.photo_name AS work_name,
A.supply_price,
A.sell_price,
sum(A.num) AS total_num,
(
A.sell_price - A.supply_price
) AS sell_profit,
(
A.sell_price - A.supply_price
) / A.sell_price AS sell_percent,
FROM
order_goods AS A
LEFT JOIN (
SELECT
A.parentid,
FROM
test_ds AS A
sql left join 多表连接
LEFT JOIN test_ds AS B ON A.parentid = B.goods_id
) AS B ds_id = B.goods_id
WHERE
atetime <= '2016-10-16 23:59:59'
AND FROM_UNIXTIME(
UNIX_atetime),
'%Y-%m-%d'
) != '2016-09-28'
AND FROM_UNIXTIME(
UNIX_atetime),
'%Y-%m-%d'
) != '2016-10-07'
GROUP BY
A.photo_id
ORDER BY
) AS A
LEFT JOIN (
SELECT
A.wid,
A.brand_id,
B.gb_name
FROM
test_qyg_user.buser_goods_list AS A
LEFT JOIN test_qyg_supplier.brands AS B ON A.brand_id = B.gbid
) AS B ON A.wid = B.wid
查询结果耗时4秒多,explain分析,发现其中2个⼦查询是全部扫描,可以使⽤mysql的多个left join优化SELECT
A.sub_order_id,
A.photo_id AS wid,
A.photo_name AS work_name,
A.supply_price,
A.sell_price,
sum(A.num) AS total_num,
(
A.sell_price - A.supply_price
) AS sell_profit,
(
A.sell_price - A.supply_price
) / A.sell_price AS sell_percent,
B.parentid,
D.brand_id,
E.gb_name,
sum(
CASE
WHEN F.buy_type = 'yes' THEN
A.num
ELSE
END
) AS total_buy_num,
sum(
CASE
WHEN F.buy_type = 'yes' THEN
A.num
ELSE
END * A.sell_price
) AS total_buy_money,
sum(
CASE
WHEN F.buy_type = 'no' THEN
A.num
ELSE
END
)
AS total_give_num,
sum(
CASE
WHEN F.buy_type = 'no' THEN
A.num
ELSE
END * A.sell_price
) AS total_give_money
FROM
order_goods AS A
LEFT JOIN test_ds AS B ds_id = B.goods_id
LEFT JOIN test_ds AS C ON B.parentid = C.goods_id
LEFT JOIN test_qyg_user.buser_goods_list AS D ON A.photo_id = D.wid
LEFT JOIN test_qyg_supplier.brands AS E ON D.brand_id = E.gbid
LEFT JOIN order_info_sub AS F ON A.sub_order_id = F.order_id
WHERE
atetime <= '2016-10-16 23:59:59'
AND FROM_UNIXTIME(
UNIX_atetime),
'%Y-%m-%d'
) != '2016-09-28'
AND FROM_UNIXTIME(
UNIX_atetime),
'%Y-%m-%d'
) != '2016-10-07'
GROUP BY
A.photo_id
ORDER BY
查询结果耗时0.04秒
更多关于MySQL相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《》希望本⽂所述对⼤家MySQL数据库计有所帮助。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论