MySQL – Advanced query based on if null and join
質問
I am trying to query several tables with one query based on the values of the joined table.
SELECT a.id,a.name,
IFNULL(b.imageurl, 'default image url') AS 'imageurl',
IFNULL(b.imagecategory, '34') AS 'imagecategory',
IFNULL(b.imagetype, 't') AS 'imagetype'
FROM summary a
LEFT JOIN images i ON a.id = b.id
WHERE b.imagetype = 'thumbnail' AND b.imagecategory = '99'
Table 'a', is the main table and consists of various information about an object.
The table 'b', consists of several image urls for each object, these are filtered using 'imagetype' and 'imagecategory' to only match one image for each object.
The join of the two tables only works if table 'b' has a matching id, imagetype and imagecategory. If not, only the records from table 'a' that has them are returned, which is not what I want. I want table 'b' to return the default values that are set using the IFNULL function, so I get a full result set even if this table is missing values for the linked id:s.
How can I do this?
解決
Try to move the tests against columns in images
to the join clause instead. When there are no matches in images
you will have null
in your columns and that does not equal anything.
SELECT a.id,a.name,
IFNULL(b.imageurl, 'default image url') AS 'imageurl',
IFNULL(b.imagecategory, '34') AS 'imagecategory',
IFNULL(b.imagetype, 't') AS 'imagetype'
FROM summary a
LEFT JOIN images b ON a.id = b.id AND
b.imagetype = 'thumbnail' AND
b.imagecategory = '99'