My use case is similar to the here. For some reason my code is not working All I want to do is, fetch products, along with it a single product image
Below is the response I receive when I run the query, but I want single row (here id=10 is returned twice because there is two image for the product)
[
{
"id": "10",
"title": "Horlicks Health & Nutrition Drink Jar",
"image": "url-8.1"
},
{
"id": "10",
"title": "Horlicks Health & Nutrition Drink Jar",
"image": "url-8.2"
}
]
I tried to run this, it works but without GROUP BY
SELECT p.*,ph.url
FROM products AS p
LEFT JOIN images AS ph
ON p.id=ph.product_id
WHERE (p.title LIKE '%hor%')
GROUP BY p.id
Error : Trying to get property 'num_rows' of non-object
Schema
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`product_id` int(11) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `images` (`id`, `product_id`, `url`) VALUES
(1, 8, 'url-8.1'),
(8, 10, 'url-8.11'),
(9, 10, 'url-8.000');
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`title` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `products` (`id`, `title`) VALUES
(8, 'Bbetter Vitamin'),
(9, 'Liveasy Essentials'),
(10, 'Horlicks Health');
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
This query also works but it uses subquery, it be cause perfomance bottleneck as its a search API having lots of search conditions
SELECT p.*, ph.url as image
FROM products AS
LEFT JOIN images AS ph
ON ph.id=(SELECT id FROM images AS pi WHERE pi.product_id = p.id LIMIT 1)
WHERE (p.title LIKE '%hor%')
This query also works but I need ph.url
, if I add it then it gives me error.
This works SELECT p.*, MIN(ph.url) as image
but I want to fetch the first image which matched
SELECT p.*, MIN(ph.id) as image_id
FROM products AS p
LEFT JOIN images AS ph
ON p.id=ph.product_id
WHERE (p.title LIKE '%hor%')
GROUP BY p.id