3

Hi I have below table structure shown in image

enter image description here

I am trying to write query in mysql to fetch

name,address,mono from customer table or vendortable depend on whoseid value from transportsticker table

I tried as

 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

But it is giving syntax error. can anybody help me...?

5
  • You can't use CASE to decide which table to join. Commented Jun 13, 2016 at 11:13
  • what should I use..? Commented Jun 13, 2016 at 11:14
  • I would go for a better table design. Combine the CustomerTable and VendorTable and keep the type there instead. Commented Jun 13, 2016 at 11:16
  • But I want data from CustomerTable or VendorTable based on whoseid column data from TransportSticker Table, then why should I combine them Commented Jun 13, 2016 at 11:17
  • Because your table design is wrong, making you attempt bad solutions like the CASE statement in a JOIN. Commented Jun 13, 2016 at 11:19

2 Answers 2

2

CASE in SQL is an expression and cannot be used to control flow of execution like in procedural languages.

You can use LEFT JOIN with COALESCE instead:

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this.

SELECT name, address, mono FROM TransportSticker, CustomerTable, VendorTable WHERE (TransportSticker.whoseid = 'vendor' AND VendorTable.id = TransportSticker.vorcid) OR (TransportSticker.whoseid = 'customer' AND CustomerTable.id = TransportSticker.vorcid)

This selects the corresponding entries from the Tables VendorTable and CustomerTable to your entries in TransportSticker.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.