2015-04-17 47 views
-1

我有兩個表。自定義的mySQL列現在顯示執行查詢時

== Table structure for table all_tasks 

|------ 
|Column|Type|Null|Default 
|------ 
|id|int(11)|No| 
|name|text|No| 


|1|Task 1 
|2|Task2 
|3|Task 3 
|4|Task 4 
|5|Task 5 
== Table structure for table task_list 

|id|int(11)|No| 
|task_list|varchar(50)|No| 
== Dumping data for table task_list 

|1|1,2,3 

第一個表(all_taska)包含了所有的任務我的應用程序,而第二個表了任務列表,從第一個表。

二表列了這task_list在陣列格式(1,2,3,4,5)

我要選擇的是insde「task_list」創造與第一表標籤的所有任務<select> <option>元素來自第二個表的數組。問題是查詢結果無法返回costom列(查詢中的「選定」)。

有人知道問題在哪裏嗎?

SELECT a.id, a.name, IF(a.id IN b.task_list, 'no selected', 'selected') as Selected 
FROM all_tasks as a LEFT JOIN task_list as b ON a.id IN (b.task_list) 
+0

存儲一組數據列內出現數據完整性錯誤 –

回答

0

你永遠不應該存儲數據作爲逗號分隔的字符串,你應該想到規範化。然而,在這種情況下,你可以使用如

select 
t1.id , 
t1.name, 
case 
    when t2.id is not null then 'selected' else 'no selected' 
end as `selected` 
from all_tasks t1 
left join task_list t2 on find_in_set(t1.id,t2.task_list) > 0 ; 
1

不能使用IN運營商在varchar清查條件。如果你想實現許多一對多的關係,您可以使用以下方案:

create table task_list (list_id int not null, task_id int not null) 

採用這種方案,您的查詢可以實現以下方式:

select t.list_id, t.id, t.name, 
     if (tl.list_id is not null, 'selected', 'no selected') as Selected 
from task_list tl right 
    join 
     (select distinct list_id, id, name from all_tasks join task_list) as t 
    on t.list_id = tl.list_id and t.id = tl.task_id;