[英]how to extract values from sql table
> ID ProductID OptionName OptionValue SKU
>
> 1 709 Title Como test
> 2 709 Color Cobalt test
> 3 709 Color Crimson RNA.331.02.MM1K
> 4 709 Title Como G2 RNA.331.02.MM1K
> 7 709 Color another color test ipn
> 8 709 Title another title test ipn
從上表中我想要以下內容
Select distinct OptionName from myTable where ProductID = 709 group by OptionValue
但是SQL Server在group by子句上給出錯誤,並且不知道如何將所有不同的值分組到不同的OptionName?
還是我不能?
我想要的結果如下
[0] => array
[Color] => array
[0] => Cobalt test
[1] => Crimson
[2] => another color
[Title] => array
[0] => Como test
[1] => Como G2
[2] => another title
當您具有GROUP BY子句時,您需要在要選擇的字段(例如FIRST(),LAST(),MAX(),AVG()...)上使用聚合函數。 另外,當您具有GROUP BY時,也不必區分。 您能否說明要提取的數據,而不僅是發布錯誤的查詢?
編輯 :
SELECT OptionName, OptionValue FROM myTable WHERE ProductID = 709 ORDER BY OptionName ASC
會產生這個:
> OptionName OptionValue
>
> Color Cobalt test
> Color Crimson
> Color another color
> Title Como test
> Title Como G2
> Title another title
轉換為數組等是您必須在應用程序中完成的工作,而不是使用SQL。
這是一個解決方案
Select OptionName from myTable where ProductID = 709 limit 1
為什么group by下划線
嘗試不帶區別的選項並在其中使用OptionValue
select OptionName
from myTable
where ProductID = 709
group by OptionName, OptionValue
使用GROUP BY將給您不同的組合。
通過使用GROUP BY OptionValue
您說的是...
-像往常一樣從我的查詢中獲取所有記錄
-組記錄具有相同的OptionValue
-每個組僅返回一條記錄
對於您的情況,然后嘗試返回OptionName。 這是一個問題,因為每個組要顯示多個OptionName,但是每個組只能顯示一個記錄。
就像已經說過的那樣,正確的查詢取決於您的需求,而我對您所寫內容的了解還不是100%清楚。 (提供所需結果的示例以及如何獲得這些結果將有所幫助。)
我的猜測是,您只需要兩個記錄( Color
和Title
)。 如果是這樣,您可以執行以下任一操作...
SELECT DISTINCT OptionName FROM myTable WHERE ProductID = 709
SELECT OptionName FROM myTable WHERE ProductID = 709 GROUP BY OptionName
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.