![](/img/trans.png)
[英]Concatenating values in mysql where multiple rows in one table relate to one row in another table
[英]JOINing two tables in MySQL when multiple rows in one table relate to one row in another
我有兩個表, module_config
和module_settings
。 后者包含具有默認值的行,而前者包含將覆蓋默認值的行。
我在此小提琴中創建了帶有一些測試行的表: http ://sqlfiddle.com/#!2/ ad4eb 。
這是我的規格:
1)我想提供的列表gid
秒。 例如,提供100
, 24
, 48
, 50
。 2)我希望查詢為每個gid
返回每個設置的行(在module_settings
給出)。 它應該忽略任何module_settings
排在那里module_settings.gid_specific
等於0
。 3)如果該行存在,則value
將等於module_config
給定的對應值,否則module_settings
給定的initial
值。
有了上面的小提琴,我想要可以返回以下內容的東西(用於輸入上述4個gid
值):
| mid----- | gid | name-------- | value |
| currency | 100 | hand_default | 12--- |
| currency | 24- | hand_default | 17--- |
| currency | 48- | hand_default | 29--- |
| currency | 50- | hand_default | 0---- |
| currency | 100 | bank_default | 0---- |
| currency | 24- | bank_default | 0---- |
| currency | 48- | bank_default | 0---- |
| currency | 50- | bank_default | 0---- |
因此,它首先在module_settings
找到gid_specific
等於1的所有行。這些行通過具有mid
和name
的唯一組合而不同。 之后,針對每個gid
每個設置返回一行。 所以對於module_setting
其中排mid
等於currency
和name
等於hand_default
,它將返回4行,每一個gid
的100
, 24
, 48
和50
。 剩下要做的唯一事情就是確定要與此行關聯的值。 如果module_config
中存在一行,其中module_config.sid
等於module_settings.id
而module_config.gid
是所討論的gid
,則使用module_config.value
給定的值,否則使用module_settings.initial
給定的默認值。
如您所見,我已經把它放在腦子里了,但我只是不敢將其放入查詢語句中。 如果有人能闡明一點,我將非常感激。
我已經使用過Teradata SQL。 我敢肯定,如果您嘗試這樣做,則可以找到SQL的等效語法。
除了您的兩個表之外,我還使用了tbl3作為您所說的來自PHP數組的gid的來源。
步驟1:交叉連接module_settings和module_config
SELECT mid,gid,name, b.value1
FROM IBB_APP.module_settings a, IBB_APP.module_config b
WHERE gid_specific = 1;
結果是
mid gid name value1
-------------------------------- ----------- -------------------------------- ----------
currency 100 hand_default 12
currency 24 hand_default 17
currency 48 hand_default 29
currency 100 bank_default 12
currency 24 bank_default 17
currency 48 bank_default 29
步驟2.包括tbl3 ,它也給出了gid = 50。
SELECT mid,c.gid,name,
CASE WHEN b.gid = c.gid THEN b.value1
WHEN b.gid IS NULL THEN a.initial1 END AS value1
FROM IBB_APP.module_settings a, IBB_APP.module_config b
RIGHT OUTER JOIN IBB_APP.tbl3 c ON (b.gid = c.gid)
WHERE gid_specific = 1
ORDER BY name,c.gid;
結果是
mid gid name value1
-------------------------------- ----------- -------------------------------- ----------
currency 24 bank_default 17
currency 48 bank_default 29
currency 50 bank_default 0
currency 100 bank_default 12
currency 24 hand_default 17
currency 48 hand_default 29
currency 50 hand_default 0
currency 100 hand_default 12
希望對您有所幫助,並且我能正確理解您的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.