简体   繁体   English

MySql LEFT连接多个具有相同ID或名称的表

[英]MySql LEFT join multiple table same with same id or name

i'm having some problems. 我有一些问题。 with the JEFT JOIN sql statement. 用JEFT JOIN sql语句。 i have 3 tables: 我有3张桌子:

user , products, prod_images. 用户,产品,prod_images。

table.user user_id 

table.products user_id item_id

table.prod_images user_id item_id

when i run this query to get data that relation, its work fine. 当我运行此查询以获取关系数据时,其工作正常。 but only work if the prod_images table are not empty. 但只有在prod_images表不为空时才有效。 when the prod_images empty the sql right join merge the result and i get null to the products.item_id array 当prod_images清空sql右连接合并结果时,我得到product.item_id数组的null

 SELECT products.*, prod_images.*, users.*
 FROM products 
 LEFT JOIN prod_images 
    ON products.item_id=prod_images.item_id
    AND prod_images.is_primary = '1'
JOIN users 
    ON users.user_id=products.seller_id 
    WHERE products.status = '1' 
    ORDER BY created DESC 

How can i make this query work fine when the table.prod_images is empty ? 当table.prod_images为空时,如何使此查询正常工作?

I believe your query is almost ok. 我相信你的查询几乎没问题。

And it returns everything you asked for, but you should avoid of requesting products.*, prod_images.*, users.* because it is easy to confuse ourselves. 它会返回您要求的所有内容,但您应该避免请求products.*, prod_images.*, users.*因为它很容易混淆我们自己。

So if you change this part at least to SELECT products.item_id PRODUCTS_ITEM_ID, products.*, prod_images.*, users.* 因此,如果您至少将此部分更改为SELECT products.item_id PRODUCTS_ITEM_ID, products.*, prod_images.*, users.*

And one another note, your query probably returns no products.item_id not when prod_images has no related records (because it LEFT JOIN ed) but when users has no related records because it is INNER JOIN ed. 而彼此记,查询可能不返回products.item_id不是当prod_images没有相关的记录(因为LEFT JOIN ED),但是当users还没有相关的记录,因为它是INNER JOIN版。 So I would start from changing JOIN users to LEFT JOIN users . 所以我会从将JOIN users改为LEFT JOIN users

PS Look at @Reno comment. PS看@Reno评论。 I did not mention that. 我没有提到这一点。 for sure you should change ON products.item_id=products.item_id to ON products.item_id=prod_images.item_id 您肯定应将ON products.item_id=products.item_id更改为ON products.item_id=prod_images.item_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM