我有
table customer {ID(primary key-autoincrement),CUSTOMERNAME}
table item {ID (primary Key-autoincrement),PRODUCT,PRICE}
table price {ID (primary key-autoincrement),CUSTOMERID (foreign key),ITEMID (foreign-key),PRICE}
现在我正在填写这样的数据:
table customer : {1,ABC},{2,DEF}
table item :{1,EGG,50},{2,BRUSH,100},{3,SHOES,290},{4,SOCKS,120},{5,PILLOW,200}
table price :{1,1,3,320}
如果我得到客户ABC的价格(客户ID:1),那么将显示这样的结果(5条记录)
{1,1,EGG,50},{2,1,BRUSH,100},{3,1,SHOES,320},{4,1,SOCKS,120},{5,1,PILLOW,200}
但如果我想显示客户DEF的价格,那么只显示4条记录
{1,1,EGG,50},{2,1,BRUSH,100},{4,1,SOCKS,120},{5,1,PILLOW,200}
我的问题如何显示商品ID(3)的商品价格,客户DEF的默认价格为290?
我在这种情况下使用左外连接然后用连接记录,然后在第二种情况下他们只返回4条记录
这里我的查询(返回4条记录)
SELECT TMP."ID",TMP."IDCUSTOMER",TMI."NAME",
CASE WHEN TMP."PRICE" IS NULL THEN TMI."PRICE" ELSE TMP."PRICE" END AS "CUSTOMPRICE"
FROM mitem TMI
LEFT OUTER JOIN mprice TMP ON TMP."IDITEM"=TMI."ID"
LEFT OUTER JOIN mcustomer TMC ON TMC."ID"=TMP."IDCUSTOMER"
WHERE TMP."IDCUSTOMER"='2' OR TMP."ID" IS NULL
除了使用UNION加入结果之外还有什么想法? 先谢谢
答案 0 :(得分:0)
使用CROSS JOIN
。
像这样:
SELECT TMP."ID",TMP."IDCUSTOMER",TMI."NAME",
CASE WHEN TMP."PRICE" IS NULL THEN TMI."PRICE" ELSE TMP."PRICE" END AS "CUSTOMPRICE"
FROM mitem TMI
CROSS JOIN mcustomer TMC
LEFT OUTER JOIN mprice TMP ON TMP."IDITEM"=TMI."ID"
AND TMP."IDCUSTOMER"= TMC."ID" AND TMP."IDCUSTOMER"= '2'
WHERE TMC."ID" = '2'