简体   繁体   中英

PHP & SQL issue: Need to echo all results possible when it doesn't return some fields

Is there a way to change this sql statement to return results it does find? Basically right now orderprc.item_no and orderprc.cust_no do not always exist in the table. So if they don't my query does not return anything.

What I want to do when they don't exist is echo everything it does find, but just leave the rest blank. I am echoing these inside a table. Any suggestions? Let me know if you need more info.

SELECT 
    ordernumber.ord_num, 
    lineitem.item_no, 
    lineitem.item_desc_1,
    ordernumber.cus_no, 
    lineitem.unit_price, 
    cic.sman, 
    orderprc.description
FROM ordernumber JOIN lineitem
ON ordernumber.ord_num = lineitem.ord_num
JOIN cicmpy ON ordernumber.cus_no = cic.debcode
JOIN orderprc ON ordernumber.cus_no = orderprc.cust_no
WHERE ordernumber.ord_num = $multi_orders
  AND orderprc.item_no = lineitem.item_no
  AND orderprc.cust_no = ordernumber.cus_no
  AND getdate() between start_dt and end_dt

Yes, use an OUTER JOIN (spelled out in SQL statements as either LEFT JOIN or RIGHT JOIN ) as opposed to an INNER JOIN. When you just use the term JOIN , it defaults to an INNER JOIN.

In your example, the SQL statement would look like:

SELECT ordernumber.ord_num, lineitem.item_no, lineitem.item_desc_1,
    ordernumber.cus_no, lineitem.unit_price, cic.sman, orderprc.description
FROM ordernumber 
    JOIN lineitem ON ordernumber.ord_num = lineitem.ord_num
        JOIN cicmpy ON ordernumber.cus_no = cic.debcode
            LEFT JOIN orderprc ON ordernumber.cus_no = orderprc.cust_no
WHERE ordernumber.ord_num = $multi_orders
    AND orderprc.item_no = lineitem.item_no
    AND orderprc.cust_no = ordernumber.cus_no
    AND getdate() BETWEEN start_dt AND end_dt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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