php - [MySQL] : Get product row - if doesn't exist by brand & product_code - get only by brand where product_code is empty

标签 php mysql sql

我有一个 shop_product_videos 表:

id |品牌 |产品代码 |链接

每次我加载页面时,它都会使用以下 MySQL 查询获取特定产品的视频:

SELECT link FROM shop_product_videos WHERE brand='$brand' AND product_code='$product_code' LIMIT 1

并显示它。

示例:

$brand = "Samsung"; 
$product_code = 111;

43 | Samsung | 111 | youtube.be/111222333

因此,如果我的页面加载名为“Samsung”的产品,并且它的“product_code”为“111”,它将显示数据库中该行的视频链接。

我想更新我的函数,以适应只有品牌名称但表中没有产品代码(空/空)的情况,并且我想显示该产品的“常规视频”(以及所有项目)有“三星”作为品牌)。

想要的结果示例:

$brand = "Samsung"; 
$product_code = 777; 

43 | Samsung | 111 | youtube.be/111222333
44 | Samsung |  | youtube.be/444555666

运行查询时,我将获得视频的第二行 (id 44),因为它没有找到与 777 product_code 完全匹配的内容

最佳答案

简单使用OR

SELECT link FROM shop_product_videos 
WHERE brand='$brand' 
AND (product_code is null or product_code='$product_code') 
LIMIT 1

更新1:

SELECT link FROM shop_product_videos 
WHERE brand='$brand' 
AND ( product_code='$product_code' or product_code='' or product_code is null) LIMIT 1

关于php - [MySQL] : Get product row - if doesn't exist by brand & product_code - get only by brand where product_code is empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564861/

相关文章:

php - 在 Laravel 中找不到驱动程序

php - Laravel - 迁移时找不到驱动程序

mysql - 排序和限制

VB.net 数据类型错误中的 SQL 数据检索

php - 如何配置 Behat 以从我的应用特定文件夹自动加载类

mysql - 使用带条件的行进行左连接

mysql - 在mysql中创建 View 时,是否可以使用日期函数?

java - JDBC - 如何更新日期 -1 的记录

sql - postgresql 查询中的问题

php - 添加 Jquery 选择下拉框以使用 raphael 美国 map 细化搜索