[英]MYSQL Query to SELECT row based on a value (if exists) otherwise return data from another table
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. 我想选择
itemName
, itemPrice
, itemCode
使用等join
两个表。
So far so good; 到现在为止还挺好; however, the row corresponding to a given
itemID
in CATALOG
may not exist in the ORDER
table. 但是,在
ORDER
表中可能不存在与CATALOG
给定itemID
对应的行。 In which case, I want to fall back on using itemName
, itemCode
from the first table CATALOG
. 在这种情况下,我想
itemCode
第一个表CATALOG
itemName
和itemCode
。
Is this possible using MYSQL in a single (compound) statement? 是否可以在单个(复合)语句中使用MYSQL?
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
. 我需要此联接,因为
CATALOG
将不包含从ORDER
获得的价格。 If I use itemID=1
there would not be a corresponding entry in ORDER
table and the query would fail. 如果我使用
itemID=1
,那么ORDER
表中将没有相应的条目,查询将失败。 I want it to retrieve at least itemName
if there is no entry for the item in ORDER
如果在
ORDER
没有该项的条目,我希望它至少检索itemName
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: 只需在两个表之间使用
LEFT OUTER JOIN
,那么您将始终在JOIN的LEFT端拥有与该表相对应的数据:
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 Os in the above selection will turn up as NULL if the item from the CATALOG
does not exist in ORDERS
. 如果
CATALOG
中的项目不存在于ORDERS
,则以上选择中的所有O将变为NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.