2014-09-27 66 views
-1

我想選擇一些數據,但是我遇到了問題,因爲這是一個子查詢,並且子查詢中的數據使用別名進行連接。我想設置這是因爲我將以不同的方式在子查詢上運行聚合。這是一個例子。我希望你明白我在這裏要做的。這不是我正在使用的實際數據,因此我想使用下面的方法。問題是我試圖查詢一個具有別名,並有一個別名的聯接的子查詢。請記住,下面的工作如果我只選擇main_query.FullState,如果我有1個連接,但由於我加入兩次,我需要添加一個別名。這是我遇到麻煩的地方。加入別名的子查詢

 
USERTABLE 
---------------- 

    Name BirthState  LivingState 
    David CA    CA 
    Roger NY    PA 
 
STATESTABLE 
---------------- 
    State FullState 

    CA  California 
    NY  New York 
    PA  Philadelphia 
select main_query.LivingTable.FullState, count(*) from (
    select * from USERTABLE 
    join STATESTABLE LivingTable on USERTABLE.LivingState = STATESTABLE.State 
    join STATESTABLE BirthTable on USERTABLE.BirthState = STATESTABLE.State 
)main_query 
+0

您的問題是,你正在使用'選擇*'。切勿使用'select *'。始終只選擇需要的列和別名。 – 2014-09-28 13:02:22

+0

@ Nick.McDermaid你是完全正確的。我最終選擇了列(40+以上),並解決了我的問題。 – KingKongFrog 2014-09-28 15:41:17

回答

0

你可以使用連接表的別名。你甚至不能訪問「內部」表別名,因爲它超出了範圍。

如果您想要檢索原始表中具有相同列名的兩列,請在AS中使用列別名。

另一件事:請對這些案件使用WITH。這極大地提高了可讀性。

WITH main_query AS 
(
    select lt.FullState AS LivingFullState, bt.FullState AS BirthFullState 
    from USERTABLE ut 
    join STATESTABLE lt on lt.LivingState = ut.State 
    join STATESTABLE bt on bt.BirthState = ut.State 
) 
select LivingFullState, count(*) from main_query 
0

您應該能夠在不訴諸「子查詢」的情況下運行「聚合」和其他類型的查詢。簡單地使用像

Select living.FullState as "Living State", count(1) 
    from USERTABLE user JOIN STATESTABLE living on living.LivingState = user.State 

類似下面的項目也可能是有用的

Select State, Sum(LivingStatePopulation) as "Living State Population", Sum(BirthStatePopulation) as "Birth State Population" 
    from (Select living.FullState as "State", count(1) as "LivingStatePopulation", 0 as "BirthStatePopulation" 
      from USERTABLE user JOIN STATESTABLE living on living.LivingState = user.State 
     UNION 
     Select birth.FullState as "State", 0 as "LivingStatePopulation", count(1) as "BirstStatePopulation" 
) 
order by State