2016-10-26 68 views
0

我有查詢,其中我得到列'月'ambigious。我正在嘗試以下查詢。請檢查nd幫助我。獲取列名ambigous

SELECT SC.name as sc, 
     B.name as brand, 
     COUNT(T.id) as tc, 
     SUM(IF(is_category_present = 1, 1, 0)) as BASE 
FROM outlet_categories OC 
    INNER JOIN transactions T ON OC.outlet_id = T.outlet_id 
    inner join outlets O on O.id = T.outlet_id 
    inner join brands B on T.brand_id = B.id 
    inner join sale_channels SC on SC.id = O.sale_channel_id 
WHERE T.month = month 
+1

使用別名 – HoneyBadger

+0

需要定義表別名在哪裏cluase WHERE T.month =月 –

+1

可能的重複[Ambiguous column name error](http://stackoverflow.com/questions/318066/ambiguous-column-name -error) – HoneyBadger

回答

1

限定您的所有列名稱。目前尚不清楚正確的名稱是什麼,但這些都需要表的別名:

關於MySQL
SELECT SC.name as sc, B.name as brand, 
     COUNT(T.id) as tc, 
-------^ Looks like an aggregation query, but there is no `GROUP BY`. 
     SUM(IF(is_category_present = 1, 1, 0)) as BASE 
--------------^ 
FROM outlet_categories OC INNER JOIN 
    transactions T 
    ON OC.outlet_id = T.outlet_id INNER JOIN 
    outlets O 
    ON O.id = T.outlet_id INNER JOIN 
    brands B 
    ON T.brand_id = B.id INNER JOIN 
    sale_channels SC 
    ON SC.id = O.sale_channel_id 
WHERE T.month = month; 
----------------^ 

三題:

  • IF()是沒有必要的。
  • 我猜month是一個變量。如果是這樣,請將其命名爲別的。
  • 想必你想要一個GROUP BY

一個更好的版本的查詢:

SELECT SC.name as sc, B.name as brand, COUNT(T.id) as tc, 
     SUM(??.is_category_present) as BASE 
FROM outlet_categories OC INNER JOIN 
    transactions T 
    ON OC.outlet_id = T.outlet_id INNER JOIN 
    outlets O 
    ON O.id = T.outlet_id INNER JOIN 
    brands B 
    ON T.brand_id = B.id INNER JOIN 
    sale_channels SC 
    ON SC.id = O.sale_channel_id 
WHERE T.month = v_month 
GROUP BY SC.name, B.name; 

變量month已更名爲v_month,所以它是沒有混淆列名。 MySQL會將T.month = month解釋爲T.month = T.month - 假設month僅在T表中。而且,我猜T.month = T.month不是你的意圖。

0

如果你有一個以上的表名爲月份列,那麼你必須指定它來自表,否則數據庫不知道你指的是哪個月份命名列。

+0

是月份字段是iin Outlet_category和事務T.你能告訴我,你是怎麼說的嗎? – sukh

0
SELECT SC.name as sc, 
     B.name as brand, 
     COUNT(T.id) as tc, 
     SUM(IF(is_category_present = 1, 1, 0)) as BASE /* <-- from with table this column? add alias*/ 
FROM outlet_categories OC 
    INNER JOIN transactions T ON OC.outlet_id = T.outlet_id 
    inner join outlets O on O.id = T.outlet_id 
    inner join brands B on T.brand_id = B.id 
    inner join sale_channels SC on SC.id = O.sale_channel_id 
WHERE T.month = month /* <-- from with table this column month? add alias*/ 

此錯誤比你在多個表中有,例如,列test和SQL不知道從哪裏拿此列 - 從表1或表2,例如。