简体   繁体   English

PHP MySQL多次连接

[英]PHP MySQL Multiple Joins

Working on an application that needs to collaborate three tables. 在需要协作三个表的应用程序上工作。 Product Offers, Transactions, Declined Offers In otherwords: (Available Products), (Purchased Products), (Products Declined, Not interested.) 产品报价,交易,拒绝的报价换句话说:(可用产品),(购买的产品),(拒绝的产品,不感兴趣。)

Product Offers Contains All product data: (Name, Desc, Price, anything shown during the while script) 产品报价包含所有产品数据:(名称,描述,价格,while脚本中显示的任何内容)

I don't want to show products if they have been purchased or declined. 我不想显示是否已购买或拒绝的产品。

For instance: 例如:

"Select * 
               JOIN Whatever
               JOIN Whatever
               (WHERE NOT IN PURCHASED OR DECLINED)";

I have a working code, for showing where not declined: 我有一个有效的代码,用于显示未拒绝的位置:

$products= "SELECT a.*, b.pID, b.userID, a.pID as pID FROM products a                   
                  LEFT JOIN declined_products b ON (a.pID = b.pID AND b.lenderID = '$userID')
                  WHERE b.pID is NULL AND b.userID is NULL
                  LIMIT $start, $maxres";

But when I try to add the second join, it no longer works... (maybe I'm using the wrong Join side? I am honestly new to joins. 但是,当我尝试添加第二个联接时,它不再起作用...(也许我使用的联接侧错误?对联接而言,我确实是新手。

$products= "SELECT a.*, b.*, c.*, a.pID as pID FROM products a                   
                  LEFT JOIN declined_products b ON (a.pID = b.pID AND                     b.lenderID = '$userID')
                  RIGHT JOIN p_transactions c ON (c.product = a.pID AND c.user_id = '$userID')
                  WHERE b.appID is NULL AND b.userID is NULL AND c.user_id <> '$userID' AND (`c.callback` != '1' or `c.callback` is NULL)
                  LIMIT $start, $maxres";

See something like this 看到这样的东西

$products= "
SELECT a.*,
    b.*,
    c.*,
    a.pID as pID
FROM
    products AS a
LEFT JOIN
    declined_products AS b ON (a.pID = b.pID AND b.lenderID = '$userID')
INNER JOIN
    p_transactions AS c ON (c.product = a.pID AND c.user_id = '$userID')
WHERE
        b.appID is NULL
    AND
        b.userID is NULL
    AND
        c.user_id <> '$userID'
    AND
        (c.callback != '1' or c.callback is NULL)
    LIMIT $start, $maxres
";

I won't get into sql injection but to say look into PDO query parameters, 我不会涉及sql注入,而是说要了解PDO查询参数,

By the way JOIN is the same as INNER JOIN, it just reads better IMO. 顺便说一句,JOIN与INNER JOIN相同,只是读取了更好的IMO。 Hardly ever will you need to use a Right Join. 您几乎不需要使用右连接。 I added AS in for the same reason I like to use INNER JOIN . 我添加AS的原因与我喜欢使用INNER JOIN原因相同。 Latter I will know it's intentional and not a typo. 我会知道这是故意的,而不是错字。 Just more readable, but that is my Opinion 'as' it works either way. 更具可读性,但这是我的观点,因为它无论哪种方式都有效。

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

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