full_price
在子查询中包含计算:
SELECT
MIN(full_price) AS min_full
, MAX(full_price) AS max_full
FROM
( SELECT IF( (SELECT COUNT(*) FROM test_table2 WHERE id = t.id) > 0
, t.price + (SELECT price FROM attribute WHERE id = t.id LIMIT 1)
, t.price
) AS full_price
FROM test_table AS t
WHERE ... --- if you want conditions applied to `test_table`
--- before calculating the `full_price`
) AS tmp ;
改进:
- (标准 SQL):use
CASE
子句而不是IF
仅适用于 MySQL 的子句。
- (性能):更改
(SELECT COUNT ...) > 0
为EXISTS (SELECT ... )
. 它通常更快。
您的查询将变为:
SELECT
MIN(full_price) AS min_full
, MAX(full_price) AS max_full
FROM
( SELECT
CASE WHEN
EXISTS (SELECT * FROM test_table2 WHERE id = t.id)
THEN t.price + (SELECT price FROM attribute WHERE id = t.id LIMIT 1)
ELSE t.price
END AS full_price
FROM test_table AS t
WHERE ...
) AS tmp ;