我四处搜索,但我没有成功尝试创建此查询以正确显示结果。我只想说,我正在寻找一些帮助我的头围绕着我可以使用的结构。基本上,我有一个包含多个产品的表(product_list)和另一个表(product_images),每个产品包含多个图片。我试图为每个产品仅提取一个图像,并将一个产品和一个图片一起显示。这是我的代码。让我知道你的想法。
SELECT `product_list`.*,
(SELECT * FROM product_images
WHERE product_list.product_tag = product_images.img_tag LIMIT 1)
FROM (`product_list`)
LEFT JOIN `product_images`
ON `product_list`.`product_tag` = `product_images`.`img_tag`
WHERE `product_list`.`product_tag` = product_images.img_tag
AND product_list.name_family = product_images.img_family
ORDER BY `date` desc LIMIT 10
答案 0 :(得分:1)
试试:
SELECT pl.*, pi.*
FROM `product_list` pl
LEFT JOIN `product_images` pi
ON pl.`product_tag` = pi.`img_tag`
AND pl.name_family = pi.img_family
GROUP BY pl.product_id -- change this to your product_id
ORDER BY `date` desc
LIMIT 10
请务必将其更改为product_id
答案 1 :(得分:1)
如果您想获得每个产品标签的一个图像,您可以这样做
SELECT p.*,
SUBSTRING_INDEX(
GROUP_CONCAT(pimg.your_image_name_column) ,',',1) `image_name`
FROM `product_list` p
LEFT JOIN `product_images` pimg
ON p.`product_tag` = pimg.`img_tag`
WHERE p.`product_tag` = pimg.img_tag
AND p.name_family = pimg.img_family
GROUP BY p.`product_tag`
ORDER BY `date` DESC LIMIT 10
您还可以在ORDER BY
GROUP_CONCAT(pimg.your_image_name_column ORDER BY some_column_from_images_table)
$this->db->select('p.*, SUBSTRING_INDEX(GROUP_CONCAT(pimg.your_image_name_column) ,',',1) `image_name`',FALSE);
$this->db->from('product_list p')
$this->db->join('product_images pimg','p.product_tag = pimg.img_tag','LEFT')
$this->db->where('p.product_tag = pimg.img_tag AND p.name_family = pimg.img_family');
$this->db->group_by("p.product_tag");
$this->db->order_by("date", "desc");
$this->db->limit(10);