使用if-else语句的MYSQL查询

时间:2016-06-13 11:12:49

标签: mysql

嗨我有下面的图表所示的表结构

enter image description here

我正在尝试在mysql中编写查询来获取

来自客户表或v​​endortable的

名称,地址,单词取决于来自transportsticker表的其中的哪个值

我试过

 SELECT transportsticker.* ,AA.name,AA.address,AA.mono FROM transportsticker INNER JOIN (case when (transportsticker.whoseid='vendor') then (vendortable) else (customertable) end) AA   ON AA.id=transportsticker.vorcid AND transportsticker.id=1

但它给出了语法错误。 任何人都可以帮助我......?

2 个答案:

答案 0 :(得分:1)

SQL中的

CASE是一个表达式,不能像过程语言那样用来控制执行流程。

您可以使用LEFT JOIN代替COALESCE

SELECT t.*, 
       COALESCE(c.name, v.name), 
       COALESCE(c.address, v.address),
       COALESCE(c.mono, v.mono) 
FROM transportsticker AS t
LEFT JOIN customertable AS c 
   ON t.whoseid='customer' AND c.id=t.vorcid
LEFT JOIN vendortable AS v
   ON t.whoseid='vendor' AND v.id=t.vorcid
WHERE t.id=1

答案 1 :(得分:0)

尝试这样的事情。

 def selectionsPartyA = [], selectionsPartyB = [], selections = [], PostChildrenSelections = [], 

PostSelections = ['7','6','5','4','3','2','1']                 

// selections
for (post in PostSelections) {
    selectionsPartyA += "dialogPartyASelection_"+post
    selectionsPartyB += "dialogPartyBSelection_"+post
    }
selections.addAll(selectionsPartyB)  
selections.addAll(selectionsPartyA)

dialogPartyASelection_7 = 'Denied'
dialogPartyBSelection_7  = 'Accepted' 
dialogPartyASelection_6 = 'Denied' 
dialogPartyBSelection_6 = 'Accepted'
dialogPartyBSelection_5 = 'Denied'
dialogPartyASelection_5 = 'Accepted'
dialogPartyBSelection_4 = 'Denied'
dialogPartyASelection_4 = 'Accepted'
dialogPartyBSelection_3 = 'Denied'
dialogPartyASelection_3 = 'Accepted'
dialogPartyBSelection_2 = 'Denied'
dialogPartyASelection_2 = 'Accepted'
dialogPartyBSelection_1 = 'Denied'
dialogPartyASelection_1 = 'Accepted' 

test = [:]
for (entry in selections){
test.put(entry, getProperty(entry))
}
assert test  == [dialogPartyBSelection_7:Accepted, dialogPartyBSelection_6:Accepted, dialogPartyBSelection_5:Denied, dialogPartyBSelection_4:Denied, dialogPartyBSelection_3:Denied, dialogPartyBSelection_2:Denied, dialogPartyBSelection_1:Denied, dialogPartyASelection_7:Denied, dialogPartyASelection_6:Denied, dialogPartyASelection_5:Accepted, dialogPartyASelection_4:Accepted, dialogPartyASelection_3:Accepted, dialogPartyASelection_2:Accepted, dialogPartyASelection_1:Accepted]

这将从Tables VendorTable和CustomerTable中选择相应的条目到您在TransportSticker中的条目。