2015-07-01 60 views
-1

我不能寫一個SQL查詢,我需要連接兩個表並獲得兩者的公共值。加入在哪裏,幷包含子句

這樣的事情,

select control_id from ProjectImage 
where group_id ="20" 
Join 
(select images from coupon where coupon_name is "test" and images contains control_id of projectImage) 

圖像是contol_id的用逗號分隔開的列表。

所以最後我只想要那些存在於優惠券的表格圖像列中的control ids

ProjectImage table ---- 
     image_id bigint(20) 
    control_id varchar(255) 
    name varchar(255) 
    project_id bigint(20)  
    group_id bigint(20) 

Coupon table: 
    id bigint(20) 
    image varchar(1250) 
    name varchar(255)  
    status int(11)  
    wafer_id bigint(20) 
+0

選擇字段從表1上其中加入表2中的結構 https://dev.mysql.com/doc/refman/5.0/en/join.html – Akhil

+6

首先,它是MySql還是Sql Server?其次,連接應該在where子句之前 –

+1

[MySQL連接where子句]的可能重複(http://stackoverflow.com/questions/1219909/mysql-join-with-where-clause) – Akhil

回答

0

,您可以加入表上的一些關鍵例如主鍵,也可以使用類似

select control_id from ProjectImage where group_id ="20" and 
control_id contains(select images from coupon where coupon_name is 
"test" and images contains control_id) 
+0

給出錯誤 - 在包含(期望一個分號) – PSDebugger

+0

包含需要列和文本,但在這裏它無法解決第二個查詢 – PSDebugger

0

,如果我得到你的問題吧,您的查詢可能應該是這樣的

SELECT ProjectImage.control_id, coupon.images 
FROM ProjectImage 
JOIN coupon ON ProjectImage.control_id = coupon.control_id 
WHERE ProjectImage.group_id ="20" 
    AND coupon.coupon_name = 'test' 

如果它不能這樣工作,請爲我們提供ProjectImage和Coupon的表格結構。

編輯 隨着提供,則可以遵循this thread和列圖像分成單獨的行,然後使用隨意加入,例如在臨時表

+2

沒有什麼像coupon.control_id。兩個表中都沒有共同的列。唯一的事情是projectImage表的control_id是優惠券表中圖像的一個子集。 – PSDebugger

+0

@PSDebugger如果沒有公共列,那麼你不能使用連接。 –

+0

唯一常見的事情是control_id在圖像中存在(圖像是不同id的集合,其中control_id將是其中的一個)。所以我需要比較projectImage表中的control_id是否存在於圖像列中,然後返回。 – PSDebugger