mysql - 如何连接没有记录的表?

标签 mysql

我有这两张表产品和愿望 list 。这是结构

enter image description here

这是愿望 list

enter image description here

这是我的问题

SELECT a.productId,productName,isNew,isHot,productImage,a.categoryId,productPrice,productDescription, 
IF(b.UserId = NULL, 1,0) as isLiked
from products a LEFT JOIN  wishlist b on (a.productId = b.productId) and (a.categoryId = b.categoryId)
where b.userId = 'usr001'

但是查询没有显示任何记录,当我删除条件时它显示产品记录。

所以我想即使使用条件也显示产品记录,我该如何解决它?

最佳答案

这按预期工作 产品展示

+----+-----------+
| id | name      |
+----+-----------+
|  1 | product 1 |
|  2 | product 2 |
|  3 | product 3 |
|  4 | product 4 |
|  5 | product 5 |
+----+-----------+
5 rows in set (0.00 sec)

create table wishlist
(userid int, productid int,name varchar(20));
insert into wishlist values
(1,1,'product 1'),
(1,3,'product 3');

select p.id,p.name,if(w.productid is null, 0 , 1 ) isliked
from products p
left join wishlist w on w.productid = p.id and p.name = w.name and w.userid = 1
order by p.id limit 5;

+----+-----------+---------+
| id | name      | isliked |
+----+-----------+---------+
|  1 | product 1 |       1 |
|  2 | product 2 |       0 |
|  3 | product 3 |       1 |
|  4 | product 4 |       0 |
|  5 | product 5 |       0 |
+----+-----------+---------+
5 rows in set (0.00 sec)

我没有看到我的模型和你的模型之间有什么区别 - 如果您将示例数据作为文本与表格定义(作为文本)一起添加到问题中,将会有所帮助。

关于mysql - 如何连接没有记录的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320980/

相关文章:

c# - 当进行非常大的插入时,不参数化 MySQL 查询而是使用方法 MySqlHelper.EscapeString(string) 是否安全?

php - 从 MySQL 到 PHP 页面选择数据

php - 数据库中编辑类别时出错

mysql - mysql 中的前导零

mysql - 如何明智地在 mysql 中应用索引

MySql 下拉过滤器选择 NULL

mysql - Node MySQL 数据库位置

mysql - Laravel 迁移中的外键约束

MySQL - 这个复杂查询的更快方法?

mysql - 查询在 Access 中有效,但在 MySQL 中无效