簡體   English   中英

如何與沒有記錄的表聯接?

[英]How to join with table that have no record?

我有這兩個表產品和願望清單。 這是結構

在此處輸入圖片說明

這是願望清單

在此處輸入圖片說明

這是我的查詢

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'

但是,當我刪除顯示產品記錄的條件時,該查詢未顯示任何記錄。

因此,即使要使用條件,我也要顯示產品記錄,該如何解決?

ON Clause使用b.userId = 'usr001'代替where clause

SELECT a.productId,productName,isNew,isHot,productImage,a.categoryId,productPrice,productDescription, 
IF(b.UserId is NULL, 1,0) as isLiked
from products a LEFT JOIN  wishlist b on (a.productId = b.productId) and (a.categoryId = b.categoryId)
and 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)

我看不到我的模型與您的模型之間的區別-如果您將示例數據作為文本與表定義(作為文本)一起添加到問題中,這將有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM