2017-02-19 81 views
2

下面是一個sql查詢,它用於獲取添加了聯繫人詳細信息的用戶列表。下面的查詢似乎工作正常。但唯一的問題是,圖像的價值總是返回NULL從子查詢中獲取選擇值

我試圖使用子查詢來圖像的圖像鏈接。除了圖像鏈接的一切工作。

SELECT a.id,a.name,a.address,a.image_id,(select url 
             from meta_details b 
             where b.p_id = 'a.image_id' 
             and b.meta_val='profile_pic') as image 
FROM users 
WHERE a.user_id NOT IN (SELECT user_id FROM details where contact_id != '$cid') 

我不確定這是否是正確的方式,是否有可能使其工作以獲取圖像url?

回答

2

您應該刪除(你有字面值'a.image_id'失敗,因爲不匹配聯接否則,而不是現場連接條件)

SELECT 
    a.id 
    ,a.name 
    ,a.address 
    ,a.image_id 
    ,(select url 
      from meta_details b 
      where b.p_id = a.image_id and b.meta_val='profile_pic') as image 
FROM users a 
WHERE a.user_id NOT IN (SELECT user_id FROM details where contact_id != '$cid') 
+0

並且還定義了表用戶別名**來自用戶的一個** –

+0

@BerndBuffen。正確..謝謝答案更新 – scaisEdge

0

周圍a.image_id報價這種類型的查詢可以也join操作來表示:

select u.*, md.url as image 
from users u left join 
    meta_details md 
    on md.p_id = u.image_id and 
     md.meta_val = 'profile_pic' left join 
    details d 
    on d.user_id = u.user_id and d.contact_id <> '$cid' 
where d.user_id is null; 

的優勢,這種方法是,SQL優化器產生更好的優化方案的機會。此外,NOT IN是危險的,因爲如果子查詢中的任何行返回NULL,則根本不會從查詢返回任何行。