如何在mysql中从连接表中查找单行数据?

时间:2014-05-04 06:42:45

标签: mysql

Product

id | name       | description
1  | one        | test        
2  | two        | test      

加入表

id | product_id | is_profile | image 
1  | 1          | 0          | 1.jpg   
2  | 1          | 0          | 2.jpg  
3  | 2          | 0          | 3.jpg  
4  | 2          | 1          | 4.jpg

如果is_profile!= 1,如何从连接表中查找单个图像字段,那么任何其他数据is_profile = 1具有is_profile = 1的特定数据? 我正在使用产品表的连接查询。 查询:

SELECT Product.*,
  (SELECT joined_table.image
   FROM joined_table
   WHERE joined_table.product_id=Product.id
     AND joined_table.is_profile=IF(joined_table.is_profile = '1', 1, 0) LIMIT 1) product_image
FROM products AS Product

2 个答案:

答案 0 :(得分:1)

您可以查看

select p.id, p.name, p.description,(select case when
(select jt.image from joined_table jt where 
 jt.product_id=p.id and jt.is_profile=1 limit 1)
is not null
then (select jt.image from joined_table jt where 
 jt.product_id=p.id and jt.is_profile=1 limit 1)
else (select jt.image from joined_table jt where 
 jt.product_id=p.id and jt.is_profile=0 limit 1)
end) as img
from Product p where p.id=2 limit 1

答案 1 :(得分:0)

 select Product.*,COALESCE((select joined_table.image from joined_table  where  joined_table.product_id=Product.id  and     joined_table.is_profile=1 limit 1), (select joined_table.image from product_picker_images  where    joined_table.product_id=Product.id  and     joined_table.is_profile=0 limit 1)) product_image from products as Product

我是用这种模式做的