2012-04-22 71 views
1

我在数据库中有两个表。一个用于产品,另一个用于产品图像。我加入的表,这样我可以有一个查询得到的产品图片和信息:左连接重复列

SELECT * 
from items left join images 
    on items.item_id = images.item_id and 
     items.display_items = '1' and items.active = '1' 
order by items.item_year desc, items.fullname desc, images.position asc 

我注意到了,但是,所有的产品均没有显示出来。一些产品没有任何图像,那些没有出现。我在Sequel Pro中运行了我的查询,看到列item_id出现两次,一次是id,一次是NULL。如何修复我的查询以获取所有产品?

回答

2

我会修改您的查询,以在结果中指定想要的确切列,而不是使用“select *”。在这种情况下,您可能在两个表中具有相同名称的列(例如“item_id”),这会在“select *”中导致问题。

另外,我会把你的ON语句的第二行放到WHERE子句中。 “items.display_items ='1'和items.active ='1'”不适用于您的加入,而是适用于您想要的一组项目。

修订查询:

SELECT --explicit list of columns 
from items 
    left join images 
    on items.item_id = images.item_id 
WHERE items.display_items = '1' and items.active = '1' 
order by items.item_year desc, items.fullname desc, images.position asc 
+0

这完美地工作。 SELECT *是问题所在。谢谢! – 2012-04-22 03:04:00

0

你缺少一个WHERE子句。假设你只想从items数据,试试这个:

SELECT it.* 
FROM items it 
LEFT JOIN images im 
ON it.item_id = im.item_id 
WHERE it.display_items = '1' and it.active = '1' 
ORDER BY it.item_year desc, it.fullname desc, im.position asc