优化一下sql语句,提高查询效率。SELECT count(DISTINCT l.user_id) as trade_num,count(DISTINCT r.user_id) as live_numFROM (SELECT DISTINCT buyer_user_id as user_id FROM trade_order_asset WHERE buyer_platform_id = 2 AND status = 10 AND is_import = 0 AND create_time >= toUnixTimestamp('2021-02-01 00:00:00') AND create_time < toUnixTimestamp('2021-03-01 00:00:00') UNION ALL SELECT DISTINCT seller_user_id as user_id FROM trade_order_asset WHERE seller_platform_id = 2 AND status = 10 AND is_import = 0 AND create_time >= toUnixTimestamp('2021-02-01 00:00:00') AND create_time < toUnixTimestamp('2021-03-01 00:00:00') ) lLEFT JOIN ( SELECT DISTINCT buyer_user_id as user_id FROM trade_order_asset WHERE buyer_platform_id = 2 AND status = 10 AND is_import = 0 AND create_time >= toUnixTimestamp('2021-01-01 00:00:00') AND create_time < toUnixTimestamp('2021-02-01 00:00:00') UNION ALL SELECT DISTINCT seller_user_id as user_id FROM trade_order_asset WHERE seller_platform_id = 2 AND status = 10 AND is_import = 0 AND create_time >= toUnixTimestamp('2021-01-01 00:00:00') AND create_time < toUnixTimestamp('2021-02-01 00:00:00') ) r ON l.user_id = toInt64(r.user_id)LEFT JOIN trade_user c ON l.user_id = toInt64(c.id)WHERE c.third_user_id not in (555136127);
时间: 2024-02-10 19:20:14 浏览: 98
可以尝试以下优化:
1. 使用索引:对于需要频繁查询的字段,创建索引可以极大提高查询效率。在这个SQL语句中,可以为以下字段创建索引:buyer_platform_id、status、is_import、create_time、seller_platform_id、buyer_user_id、seller_user_id、third_user_id、id。
2. 减少子查询:子查询的使用会增加查询的时间,可以尝试使用JOIN或者其他方式替代子查询。在这个SQL语句中,可以将子查询替换为JOIN。
3. 减少重复查询的数据:在这个SQL语句中,有多个子查询或者JOIN查询中的条件都是相同的,可以将这些条件提取出来,避免重复查询。
优化后的SQL语句如下:
SELECT
COUNT(DISTINCT l.user_id) AS trade_num,
COUNT(DISTINCT r.user_id) AS live_num
FROM
(
SELECT DISTINCT
buyer_user_id AS user_id
FROM
trade_order_asset
WHERE
buyer_platform_id = 2
AND status = 10
AND is_import = 0
AND create_time >= toUnixTimestamp('2021-02-01 00:00:00')
AND create_time < toUnixTimestamp('2021-03-01 00:00:00')
UNION ALL
SELECT DISTINCT
seller_user_id AS user_id
FROM
trade_order_asset
WHERE
seller_platform_id = 2
AND status = 10
AND is_import = 0
AND create_time >= toUnixTimestamp('2021-02-01 00:00:00')
AND create_time < toUnixTimestamp('2021-03-01 00:00:00')
) l
LEFT JOIN
(
SELECT DISTINCT
buyer_user_id AS user_id
FROM
trade_order_asset
WHERE
buyer_platform_id = 2
AND status = 10
AND is_import = 0
AND create_time >= toUnixTimestamp('2021-01-01 00:00:00')
AND create_time < toUnixTimestamp('2021-02-01 00:00:00')
UNION ALL
SELECT DISTINCT
seller_user_id AS user_id
FROM
trade_order_asset
WHERE
seller_platform_id = 2
AND status = 10
AND is_import = 0
AND create_time >= toUnixTimestamp('2021-01-01 00:00:00')
AND create_time < toUnixTimestamp('2021-02-01 00:00:00')
) r
ON l.user_id = r.user_id
LEFT JOIN
trade_user c
ON l.user_id = c.id
WHERE
c.third_user_id NOT IN (555136127)
阅读全文