如何在没有ifnull的情况下获得相同的结果-mysql

bf1o4zei  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(351)

我举了个例子:http://sqlfiddle.com/#!9/3 BBB6天/1/0

SELECT
        `Image`.`id`,
        `Topic`.`title`
    FROM
        `images` AS `Image`, `topics` AS `Topic`
    WHERE
        `Image`.`vender_id` = 'model' AND `Topic`.`id` = IFNULL((SELECT article_id FROM articles_images WHERE image_id = `Image`.`id` ORDER BY id DESC LIMIT 0, 1), 999)
    ORDER BY
        `Image`.`id` DESC
    LIMIT 10

结果:(正确)

id  title
8   
7   
5   CCC
4   DDD
3   BBB
2   BBB
1

没有 IFNULL(..., 999) http://sqlfiddle.com/#!9/3 bbb6天/2
结果:

id  title
5   CCC
4   DDD
3   BBB
2   BBB

但是我也需要有空“title”=>id:8,7和1的记录
有没有一种不使用ifnull就拥有所有记录的方法?
+更新+
@已由\u使用
谢谢你的帮助。我得到结果:(它有两个id为5的记录)

id  title
8   (null)
7   (null)
5   AAA              << X
5   CCC              << correct 
4   DDD
3   BBB
2   BBB
1   (null)

有两个id相同的记录:5,如何仅获取其中一个id最高的记录?
我需要得到的结果是:

id  title
8   
7   
5   CCC
4   DDD
3   BBB
2   BBB
1
sbtkgmzw

sbtkgmzw1#

使用左连接:

SELECT
     I.id
    ,T.title
FROM images AS i
LEFT JOIN articles_images AS ai ON I.id = ai.image_id
LEFT JOIN topics AS t on ai.article_id = t.id
WHERE i.vender_id = 'model' 
ORDER BY
    i.id DESC
LIMIT 10

结果与您要求的结果略有不同:

+----+-------+
| id | title |
+----+-------+
|  8 | NULL  |
|  7 | NULL  |
|  5 | AAA   |
|  5 | CCC   |
|  4 | DDD   |
|  3 | BBB   |
|  2 | BBB   |
|  1 | NULL  |
+----+-------+

对于重新修改的问题(包括空值):

SELECT
     I.id
    ,max(T.title) as title
FROM images AS i
LEFT JOIN articles_images AS ai ON I.id = ai.image_id
LEFT JOIN topics AS t on ai.article_id = t.id
WHERE i.vender_id = 'model' 
GROUP BY
     I.id
;

+----+-------+
| id | title |
+----+-------+
|  1 | NULL  |
|  2 | BBB   |
|  3 | BBB   |
|  4 | DDD   |
|  5 | CCC   |
|  7 | NULL  |
|  8 | NULL  |
+----+-------+

请参见:https://rextester.com/lcobw94449
为了保证您使用的是最高的文章\u,如果我建议:

SELECT
     I.id
    ,T.title
FROM ximages AS i
LEFT JOIN (
            SELECT image_id, max(article_id) article_id
            FROM xarticles_images
            GROUP BY image_id
          ) AS ai ON I.id = ai.image_id
LEFT JOIN xtopics AS t on ai.article_id = t.id
WHERE i.vender_id = 'model' 
ORDER BY
    i.id DESC
;
piztneat

piztneat2#

使用左连接

SELECT
        i.`id`,
        t.`title`
    FROM
        `images` AS i left join `topics` AS  t on  i.`vender_id` = 'model' 
         and t.`id`=i.article_id

相关问题