1

I have two tables:

CATALOG:
------------------------------------
| itemID    | itemCode  | itemName |
------------------------------------

ORDER:
----------------------------------------------
| orderID   | itemID_FK | itemPrice | etc... |
----------------------------------------------

I want to select itemName, itemPrice, itemCode etc by using a join on both tables.

So far so good; however, the row corresponding to a given itemID in CATALOG may not exist in the ORDER table. In which case, I want to fall back on using itemName, itemCode from the first table CATALOG.

Is this possible using MYSQL in a single (compound) statement?

EDIT: Here's a sample table

CATALOG:
------------------------------------
| itemID    | itemCode  | itemName |
------------------------------------
|  1        |  89873232 | Oats     |
|  2        |  32849392 | Beer     |
------------------------------------

ORDER:
----------------------------------------------
| orderID   | itemID_FK | itemPrice | etc... |
----------------------------------------------
| 213232    |  2        |  3.99     |  ...   |
----------------------------------------------

I use the following query to retrieve complete data about an item:

SELECT itemID, itemName, itemPrice FROM CATALOG
INNER JOIN ORDER
ON itemID = itemID_FK
WHERE itemID = %d

I need this join because CATALOG will not contain price which is obtained from ORDER. If I use itemID=1 there would not be a corresponding entry in ORDER table and the query would fail. I want it to retrieve at least itemName if there is no entry for the item in ORDER

3
  • 4
    What do you currently join on? Can you give your current query? If you do ...FROM CATALOG LEFT JOIN ORDER ON CATALOG.itemID=ORDER.itemID_FK then you'll always get rows from ORDER for each row in CATALOG, an if it can't find it you'll have NULL in that column. Commented Jan 18, 2012 at 5:12
  • Can you show some sample data and an example of the resultset you're after? Commented Jan 18, 2012 at 5:13
  • Added a sample table and more info. See my edit. Commented Jan 18, 2012 at 5:25

1 Answer 1

1

Just use a LEFT OUTER JOIN between the two tables, so you will always have data corresponding to the table on the LEFT side of the JOIN:

SELECT C.itemName, C.itemCode, O.itemPrice, ...
FROM CATALOG as C
     LEFT OUTER JOIN ORDER AS O ON C.itemID = O.itemID_FK

All the O.s in the above selection will turn up as NULL if the item from the CATALOG does not exist in ORDERS.

Sign up to request clarification or add additional context in comments.

1 Comment

The OUTER keyword is redundant. A LEFT JOIN is implicitly outer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.