2012-12-28 30 views
2

我使用Joomla 2.5。我正在使用MYSQL數據庫。 我有一個表job_field有以下的列:如何編寫用於比較具有逗號分隔值的列的查詢?

cat_id | location_id 
----------------------- 
1,4 | 66,70 

我需要將它與另一臺job_value

cat_id | location_id | name 
-------------------------------- 
1  | 70   | Atul 
4  | 70,80  | Amit 
4  | 80,66  | Amol 
1  | 66   | Pritam  
3  | 70   | Rahul 
2  | 66,90  | Ajit 
1  | 74   | Raju 
4  | 65,22  | Manoj 

我想輸出從第一臺job_details與第二個表比較cat_idlocation_id列比較job_valuecat_idlocation_id

它將檢查從第一表(job_details)的每個值是location_id列值(66,70)分別與第二表(job_valuelocation_id柱。我會得到輸出數組作爲

Array (
    1 70  Atul 
    4 70,80 Amit 
    4 80,66 Amol 
    1 66  Pritam 
) 
+0

您使用的是什麼RDBMS? –

+8

這不是一個標準化的結構。基本上:你註定了 - 除非你重新考慮結構。 – ppeterka

+0

以特定的sql語言方言?它是否只有一個或兩個用逗號分開的值? – rene

回答

3

這是一個結構。即使問題能夠解決,也不應該解決。這將是緩慢的,不可維護的。

而是窮人結構,這些方針的東西應該爲DB的這一部分創建:

CREATE TABLE PERSON (
    person_id BIGINT, 
    name VARCHAR(64), 
    PRIMARY KEY (person_id) 
); 

CREATE TABLE LOCATION (
    location_id BIGINT, 
    name VARCHAR(64), 
    PRIMARY KEY (location_id) 
); 
CREATE TABLE CAT (
    cat_id BIGINT, 
    name VARCHAR(64), 
    PRIMARY KEY (cat_id) 
); 

CREATE TABLE CAT_LOCATION (
    cat_id BIGINT, 
    location_id BIGINT, 
    PRIMARY KEY (cat_id,location_id), 
    FOREIGN KEY (cat_id) REFERENCES cat(cat_id), 
    FOREIGN KEY (location_id) REFERENCES location(location_id) 
); 

CREATE TABLE CAT_LOCATION_PERSON (
    cat_id BIGINT, 
    location_id BIGINT, 
    person_id BIGINT, 
    PRIMARY KEY (cat_id,location_id,person_id), 
    FOREIGN KEY (cat_id) REFERENCES cat(cat_id), 
    FOREIGN KEY (location_id) REFERENCES location(location_id), 
    FOREIGN KEY (person_id) REFERENCES person(person_id) 
); 

然後它比簡單的更容易得到你想要的東西做簡單連接:

SELECT cl.cat_id, cl.location_id, p.name 
FROM CAT_LOCATION cl 
JOIN CAT_LOCATION_PERSON clp on cl.cat_id = clp.cat_id and cl.location_id=clp.location_id 
JOIN PERSON p on clp.person_id = p.person_id 

(我拒絕編寫一個查詢,將提供指定格式的輸出,用數值用逗號隔開......(雖然有可能通過MySQL的GROUP_CONCAT功能容易))