【问题标题】:mysql Fallback to another record if first not existmysql 如果第一次不存在则回退到另一条记录
【发布时间】:2019-07-03 06:47:08
【问题描述】:

我有两个用于广告素材及其缩略图的表格。我想以一种后备方式查询,例如:

Initially, the thumbnail will be displayed for 300x250
IF not available then 336x280, 
IF not available then 300x600, 
IF not available then 728x90, 
IF not available then 160x600, 
IF not available then 320x50, 
IF not available then 300x50, 
IF not available then 468x60

表结构是这样的

creatives:
id INT
name VARCHAR
desc TEXT

creative_thumbs:
id
creative_id INT
dimension VARCHAR
img_url VARCHAR

我已经使用多个连接(每个维度一个,但有点慢)

【问题讨论】:

  • 请使用minimal reproducible example的指导添加示例数据。
  • 请添加您尝试过的内容,这样我们就不会浪费时间提出您已经尝试过的内容。

标签: mysql join background-image fallback multiple-join-rows


【解决方案1】:

您可以使用多个 LEFT JOIN 查询来做到这一点。应该是这样的:

SELECT
    c.Name AS CreativeName,
    COALESCE(
        ct1.Dimension,
        ct2.Dimension,
        ct3.Dimension,
        ct4.Dimension,
        ct5.Dimension,
        ct6.Dimension,
        ct7.Dimension,
        ct8.Dimension
        ) AS ThumbnailDimension
FROM creatives c
LEFT JOIN creative_thumbs ct1 ON c.id = ct1.creative_id AND ct1.Dimension = '300x250'
LEFT JOIN creative_thumbs ct2 ON c.id = ct2.creative_id AND ct2.Dimension = '336x280'
LEFT JOIN creative_thumbs ct3 ON c.id = ct3.creative_id AND ct3.Dimension = '300x600'
LEFT JOIN creative_thumbs ct4 ON c.id = ct4.creative_id AND ct4.Dimension = '728x90'
LEFT JOIN creative_thumbs ct5 ON c.id = ct5.creative_id AND ct5.Dimension = '160x600'
LEFT JOIN creative_thumbs ct6 ON c.id = ct6.creative_id AND ct6.Dimension = '320x50'
LEFT JOIN creative_thumbs ct7 ON c.id = ct7.creative_id AND ct7.Dimension = '300x50'
LEFT JOIN creative_thumbs ct8 ON c.id = ct8.creative_id AND ct8.Dimension = '468x60'
;

如果速度太慢,请尝试将索引添加到 Dimension 列:

CREATE INDEX creative_thumbs_Dimension_index
    on creative_thumbs (Dimension);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2018-03-02
    • 2013-12-27
    • 1970-01-01
    • 2014-06-17
    相关资源
    最近更新 更多