通过在MYSQL中重用派生字段列名来简化查询字符串

时间:2012-12-05 13:06:42

标签: mysql select simplify

我们是否仍然可以通过使用派生列作为另一个过程的输入来简化此查询

$query = "SELECT   table1.id,
         COUNT(DISTINCT arr1.element) AS Arr1,
         COUNT(DISTINCT arr2.element) AS Arr2,
         COUNT(DISTINCT arr1.element) +
         COUNT(DISTINCT arr2.element) AS tot,
(COUNT(DISTINCT arr1.element)/(COUNT(DISTINCT arr1.element)+COUNT(DISTINCT arr2.element)))*col3 AS c31,
(COUNT(DISTINCT arr2.element)/(COUNT(DISTINCT arr1.element)+COUNT(DISTINCT arr2.element)))*col3 AS c32
FROM table1 
WHERE col2 = 'x'" 

类似这样的事情

$query = "SELECT   table1.id,
         COUNT(DISTINCT arr1.element) AS Arr1,
         COUNT(DISTINCT arr2.element) AS Arr2,
         COUNT(DISTINCT arr1.element) +
         COUNT(DISTINCT arr2.element) AS tot,
        (Arr1/tot)*col3 AS c31,
        (Arr2/tot)*col3 AS c32
FROM  table1 
WHERE col2 = 'x'" 

感谢

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

$query = "
SELECT tab.id, tab.Arr1, tab.Arr2, tab.tot, (tab.Arr1/tab.tot) as c31, (tab.Arr2/tab.tot) as c32
from (
SELECT   table1.id,
         COUNT(DISTINCT arr1.element) AS Arr1,
         COUNT(DISTINCT arr2.element) AS Arr2,
         COUNT(DISTINCT arr1.element) +
         COUNT(DISTINCT arr2.element) AS tot
FROM table1 
WHERE col2 = 'x'
) as 'tab' " 

答案 1 :(得分:0)

试试这个:

SELECT id, Arr1, Arr2, (Arr1 + Arr2) tot, ((Arr1 / (Arr1 + Arr2)) * col3) c31, ((Arr2 / (Arr1 + Arr2)) * col3) c32
FROM (SELECT table1.id, COUNT(DISTINCT arr1.element) AS Arr1, COUNT(DISTINCT arr2.element) AS Arr2, col3
FROM table1 WHERE col2 = 'x') AS A