如何在mysql中比较2表

时间:2015-12-20 08:53:55

标签: mysql

我有两个名为joy_galleryjoy_category的表。

  • joy_gallery

    ╔════╦════════╦════════╗
    ║ id ║ cat_id ║ images ║
    ╠════╬════════╬════════╣
    ║ 1  ║ 1      ║ a.png  ║
    ║ 2  ║ 1      ║ a1.png ║
    ║ 3  ║ 2      ║ b1.png ║
    ║ 4  ║ 1      ║ c.jpg  ║
    ║ 5  ║ 2      ║ d.jng  ║
    ║ 6  ║ 2      ║ a1.png ║
    ╚════╩════════╩════════╝
    
  • joy_category

    ╔═════╦══════════╦═════════════╗
    ║ Cid ║ category ║ Description ║
    ╠═════╬══════════╬═════════════╣
    ║ 1   ║ onam     ║ xcfghhyjkk  ║
    ║ 2   ║ xmas     ║ hjytigkuyy  ║
    ╚═════╩══════════╩═════════════╝
    

我将比较两个表格,显示两个类别以及每个类别的最后一个图片,1 onam c.jpg1 xmas a1.jpg。我正在使用这个mysql代码:

SELECT * 
FROM joy_gallery INNER JOIN joy_category ON joy_gallery.cat_id = joy_category.Cid
ORDER BY joy_category.Cid DESC;

但它不起作用。显示同一类别的第一类和2幅图像。我怎么解决这个问题?如何显示某个类别的最后一张图片?

5 个答案:

答案 0 :(得分:1)

试试这个:

SELECT j1.* FROM joy_gallery j1
  JOIN (SELECT cid, MAX(cid) id FROM joy_category GROUP BY cid) j2
    ON j1.cat_id = j2.cid ;

答案 1 :(得分:0)

可能有更有效的方法,但一种解决方案是:

SELECT cat_id, images 
FROM 
    (SELECT MAX(galI.gaid) gaid 
    FROM joy_gallery galI INNER JOIN joy_category cat 
    ON galI.cat_id = cat.Cid GROUP BY cat_id) galIn 
INNER JOIN joy_gallery gal USING(gaid);

答案 2 :(得分:0)

您的查询可能如下所示:(tested

SELECT joy_category.Cid, joy_category.category, joy_gallery.images FROM joy_gallery
JOIN joy_category
ON joy_gallery.cat_id = joy_category.Cid AND 
joy_gallery.id IN (
    SELECT MAX(joy_gallery.id)
    FROM joy_gallery
    GROUP BY joy_gallery.cat_id
)

输出:

 Cid    category    images  
----------------------------
  1       onam       c.jpg
  2       xmas      a1.png

答案 3 :(得分:0)

尝试此查询

SELECT a.Cid, a.category, c.images
FROM joy_category a
LEFT JOIN (
     SELECT max(gaid) as id, cat_id
     FROM joy_gallery
     GROUP BY cat_id
) b ON b.cat_id = a.Cid
LEFT JOIN joy_gallery c ON c.gaid = b.id

注意:这没有经过测试,但我认为它有效。

答案 4 :(得分:0)

尝试此查询

SELECT
    r.Cid,
    r.category,
    b.images 
FROM
    joy_category b
JOIN joy_gallery r ON r.Cid  = b.cat_id 
AND r.id = (
    SELECT
        MAX (x.id)
    FROM
        joy_gallery x
    WHERE
        x.cat_id  = b.Cid 
);