Trying to get a value from 5 different tables base

2020-04-28 07:50发布

问题:

I'm trying to get the date value from 5 different tables based on the usertype value and display it on DATATABLES table.

For example :- if usertype value is 2 than I want to get the date value from table table_two.

Here is what I have got so far :

SELECT 
CASE 
WHEN tm.usertype = 1 THEN type_1.date 
WHEN tm.usertype = 2 THEN type_2.date 
WHEN tm.usertype = 3 THEN type_3.date 
WHEN tm.usertype = 4 THEN type_4.date 
WHEN tm.usertype = 5 THEN type_5.date 
END, 
tm.id,
tm.usertype
FROM table_main tm 
LEFT JOIN table_one type_1 ON tm.id=type_1.uid 
LEFT JOIN table_two type_2 ON tm.id=type_2.uid 
LEFT JOIN table_three type_3 ON tm.id=type_3.uid 
LEFT JOIN table_four type_4 ON tm.id=type_4.uid 
LEFT JOIN table_five type_5 ON tm.id=type_5.uid 

The error I'm getting from DATATABLES is:-

DataTables warning: table id=example - An SQL error occurred: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'date' in 'field list'

回答1:

Your question is clearly caused by a column not having the name you expect. However, your query may still not return what you want, because id values could (at least in theory) be shared among tables.

It is better to move the conditional logic to the on clause:

SELECT COALESCE(type_1.date, type_2.date, type_3.date, type_4.date, type_5.date) 
       tm.id, tm.usertype
FROM table_main tm LEFT JOIN
     table_one type_1
     ON tm.id = type_1.uid AND tm.usertype = 1 LEFT JOIN
     table_two type_2
     ON tm.id = type_2.uid AND tm.usertype = 2 LEFT JOIN
     table_three type_3
     ON tm.id = type_3.uid AND tm.usertype = 3 LEFT JOIN
     table_four type_4
     ON tm.id = type_4.uid AND tm.usertype = 4 LEFT JOIN
     table_five type_5
     ON tm.id = type_5.uid AND tm.usertype = 5 ;

This won't fix the specific error you have. For that, you need to fix the column names.



标签: mysql sql case