我有查詢有子查詢作爲字段列,但我想在其他地方使用此字段列。使用子查詢作爲字段列
SELECT c.country_code AS
country_code,
c.dial_code AS
dial_code,
(SELECT r.destination
FROM region r
WHERE r.country_code = c.country_code
AND r.dial_code = c.dial_code) AS
destination,
c.start_time,
c.duration,
c.call_type,
c.customer_prefix AS
customer_prefix,
c.vendor_prefix AS
vendor_prefix,
(SELECT Round(r.rate, 3)
FROM rate r
INNER JOIN region re
ON r.region_id = re.id
INNER JOIN account_prefix ap
ON r.account_prefix_id = ap.id
WHERE re.country_code = c.country_code
AND re.dial_code = c.dial_code
AND ap.prefix = c.customer_prefix
AND ap.prefix_type = 0) AS
**customer_rate**,
(SELECT Round(r.rate, 3)
FROM rate r
INNER JOIN region re
ON r.region_id = re.id
INNER JOIN account_prefix ap
ON r.account_prefix_id = ap.id
WHERE re.country_code = c.country_code
AND re.dial_code = c.dial_code
AND ap.prefix = c.vendor_prefix
AND ap.prefix_type = 1) AS
**vendor_rate**,
(SELECT Round(r.rate, 3)
FROM rate r
INNER JOIN region re
ON r.region_id = re.id
INNER JOIN account_prefix ap
ON r.account_prefix_id = ap.id
WHERE re.country_code = c.country_code
AND re.dial_code = c.dial_code
AND ap.prefix = c.customer_prefix
AND ap.prefix_type = 0) - (SELECT Round(r.rate, 3)
FROM rate r
INNER JOIN region re
ON r.region_id = re.id
INNER JOIN account_prefix ap
ON r.account_prefix_id
= ap.id
WHERE
re.country_code = c.country_code
AND re.dial_code = c.dial_code
AND ap.prefix = c.vendor_prefix
AND ap.prefix_type = 1) AS **unit_profit**,
unit_profit * duration
FROM cdr c
LIMIT 100;
正如你所看到的,我想要使用unit_profit,customer_rate和vendor_rate。如何實現它?
編輯:
任何教程顯示加入視圖?
您不能直接使用在同一個SELECT列表中定義的別名。您將需要使用外部查詢,或者(如果您的RDBMS支持它)CTE。 – 2013-03-08 02:02:37
請詳細說明外部查詢。什麼是CTE?我正在使用mysql數據庫。 – peterwkc 2013-03-08 02:35:16
Erwin Brandstetter的答案給出了一個外部查詢的例子(額外的SELECT FROM所有內部查詢,CTE代表* Common Tables Expressions *(我正在考慮'WITH'),但顯然MySQL不支持它 – 2013-03-08 02:41:13