Domanda

I have two tables that I want to join in MySQL. The first is a table of catalog items - each item has an item_id field. I also have a table of images that are associated with the items (item_id, image_id, content).

How can I join these two tables, so that I have a list of all of the items, but also include one tuple from the images table for that item?

I want to be able to generate a list of all items, with ONE image that's associated.

I've tried:

SELECT  * From items i
JOIN    images im
ON      im.image_id = 
    (
    SELECT  im.image_id
    FROM    images ci
    WHERE   ci.item_id = i.item_id
    ORDER BY
            ci.item_id
    LIMIT 1
    )

but that still just gives me only items that have an image associated with it... i need all items regardless of whether there's an image (left outer join?).

Thanks!!!!

È stato utile?

Soluzione

You need a left join to get also results where no match exists in the other table

SELECT i.*, min(im.image_id)
From items i
LEFT OUTER JOIN images im ON im.image_id = i.item_id
GROUP by i.item_id

See this great explanation of joins

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top