简体   繁体   English

如何在PHP中运行三个表INNER JOIN?

[英]How do I run three table INNER JOIN in PHP?

I need to query several tables for "product tags", based on the producttags table, and subcategorytags table. 我需要根据producttags表和subcategorytags表在几个表中查询“ product tags”。

Then to produce products where a tag is "shirt". 然后生产标签为“衬衫”的产品。

If I remove the first inner join, and the " WHERE t.producttag = 'shirt' ", it works. 如果删除第一个内部WHERE t.producttag = 'shirt' ,并且删除“ WHERE t.producttag = 'shirt' ”,那么它将起作用。 Same for the subcategorytags section. 与subcategorytags部分相同。

But when I try it with both, it doesn't error, but doesn't product anything. 但是,当我同时尝试两者时,它不会出错,但是不会产生任何结果。

SELECT p.datebackinstock, p.datepricedrop, p.id, p.catid, p.subid, p.catname, p.subname, 
       p.title, p.price, p.photoprimary, p.comingsoon, p.rcstock, p.preorder, 
       p.bundleroman1, p.bundleroman2, p.bundleroman3, p.bundleroman4, p.bundleroman5, 
       p.pricedrop  FROM products AS p 

INNER JOIN producttags AS t ON p.id = t.prodid

INNER JOIN subcategorytags AS s ON p.subid = s.subid 

WHERE t.producttag = 'shirt' OR s.tag = 'shirt'

You will have to use left joins for this as you do not know wich tags are set. 您将为此使用左连接,因为您不知道设置了标记。 In your query the row will only be returned if a producttag and a subcategorytag is found. 在您的查询中,仅当找到产品producttag subcategorytag producttag 才返回该行。 A left join will return the row even if no row in another table is found. 即使在另一个表中未找到行,左联接也会返回该行。 Because of this you will also need to do an extra check to make sure the values are not null. 因此,您还需要进行额外的检查以确保值不为空。

SELECT p.datebackinstock, p.datepricedrop, p.id, p.catid, p.subid, p.catname, p.subname, 
       p.title, p.price, p.photoprimary, p.comingsoon, p.rcstock, p.preorder, 
       p.bundleroman1, p.bundleroman2, p.bundleroman3, p.bundleroman4, p.bundleroman5, 
       p.pricedrop  FROM products AS p 

LEFT JOIN producttags AS t ON p.id = t.prodid

LEFT JOIN subcategorytags AS s ON p.subid = s.subid 

WHERE (t.producttag NOT NULL AND t.producttag = 'shirt') OR (s.tag NOT NULL AND s.tag = 'shirt')

More information about right and left joins can be found in the mysql docs . 可以在mysql docs中找到有关左右联接的更多信息。

I'd use left outer join or rather, I would try, I think like: 我会使用left outer join或更确切地说,我会尝试:

select
    p.`datebackinstock`, 
    p.`datepricedrop`, 
    p.`id`, 
    p.`catid`, 
    p.`subid`, 
    p.`catname`, 
    p.`subname`, 
    p.`title`, 
    p.`price`, 
    p.`photoprimary`, 
    p.`comingsoon`, 
    p.`rcstock`, 
    p.`preorder`, 
    p.`bundleroman1`, 
    p.`bundleroman2`, 
    p.`bundleroman3`, 
    p.`bundleroman4`, 
    p.`bundleroman5`, 
    p.`pricedrop` 
    from `products` p 
    left outer join `producttags` t on p.`id` = t.`prodid`
    left outer join `subcategorytags` s on p.`subid` = s.`subid`
    where t.`producttag` = 'shirt' or s.`tag` = 'shirt'

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

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