![](/img/trans.png)
[英]Mysql query to get rows of a table as columns of another, with column names from third table
[英]MYSQL Query matching column names to rows in another table
我在MYSQL中有兩個表,一個包含客戶可以選擇的選項列表,另一個包含選項的成本。 我想要一個返回每個客戶選項集成本的視圖。 在我的示例中,我將使用購買新車的類比。
客戶表
customer - sunroof - mag_wheels - spoiler
--------------------------------------------------
John - true - true - false
Steve - false - true - false
Lucy - false - false - false
選項表
option - price
-----------------
sunroof - 100
mag_wheels - 150
spoiler - 75
所需結果
customer - cost
-----------------
John - 250
Steve - 150
Lucy - 0
或那樣做,因為我很容易將選擇的價格乘以然后按客戶分組
customer - option - selected - price
------------------------------------------
John - sunroof - true - 100
John - mag_wheels - true - 150
John - spoiler - false - 75
Steve - sunroof - false - 100
Steve - mag_wheels - true - 150
Steve - spoiler - false - 75
Lucy - sunroof - false - 100
Lucy - mag_wheels - false - 150
Lucy - spoiler - false - 75
我已經花了幾個小時對此感到困惑,而且我什至不知道從哪里開始,因為沒有通用的元素可以匹配,所以加入似乎是不可能的。 我想知道是否使用UNION是答案,但是我不知道如何將行值與列標題結合起來。
如果有人能向我指出正確的方向,我將不勝感激,如果您想出一種可以動態選擇不同選項的解決方案,則可以加倍加分,這樣以后我就可以在不重寫查詢的情況下添加更多內容。
提前謝謝了。
我希望將所有選項都包含在一行中的原因是,我希望使用Access來創建用於選擇選項的表單,但我無法弄清楚單個表單如何創建多行。
這是一個可怕的數據布局。 您應該有一個關聯表,每個客戶和一個選項一行。
但是,您可以這樣做:
select c.customer, sum(o.cost) as cost
from customers c left outer join
options o
on (c.sunroof = true and o.option = 'sunroof' or
c.mag_wheels = true and o.option = 'mag_wheels' or
c.spoiler = true and o.option = 'spoiler'
)
group by c.customer;
編輯:
您不希望所有選項都在一個記錄中。 相反,您需要一個關聯表:
create table customer_options (
customer_optionid unsigned auto_increment,
customer varchar(255) references customer(name),
option varchar(255) references option(option)
);
實際上,您實際上應該為所有表都使用整數主鍵,並將其用於外鍵引用。 如果在問題的輸出中需要數據,則只需編寫查詢以該格式返回它。
從表結構來看,即使我認為也無法編寫聯接,因為正如您所提到的,表結構之間沒有關系。
我假設您剛剛啟動了該項目,所以現在是時候重新訪問您的數據庫結構並對其進行更正了。
理想情況下,您應該有一個帶有客戶ID的客戶表。 然后,您應該具有帶有產品ID的產品表。 一個表,其中包含有關客戶購買了哪些產品的數據-例如customer_products。 這將是一對多的關系。 因此,客戶1可以擁有產品1,3和5。這意味着在customer_product中將存在三個條目。
然后,當您要進行總計時,您可以首先將表customer加入到基於customer_product的產品中,然后再對價格進行求和,以獲得單個客戶的總金額。
設計不良。 您必須有一個customers表,如下所示:
custumer_id
customer_name
other fileds...
另一方面,您應該有一個配件表,通常在其中描述每個項目-
accesory_id
accesory_name
supplier_id
country_of_origin
other stuff
也是accesory_price表,其中由於價格變化而在其中添加價格。
accesory_id
price
active_price
date_price_added
最后,您應該將所有內容關聯到一個customer_accesory表中:
customer_id
accesory_id
通過此操作,您可以聯接表並選擇客戶購物籃大小和客戶偏好的配件。 購物籃大小或每個客戶購買的金額都可以匯總為SUM
, AVG
, COUNT
,也可以使用GROUP_CONCAT
進行數據透視以生成高質量的報告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.