我有三个表:
产品
+----+-----------------------------------------------------+
| id | title |
+----+-----------------------------------------------------+
| 1 | Lorem Ipsum is simply dummy text of the printing: 1 |
| 2 | Lorem Ipsum is simply dummy text of the printing: 2 |
| 3 | Lorem Ipsum is simply dummy text of the printing: 3 |
| 4 | Lorem Ipsum is simply dummy text of the printing: 4 |
| 5 | Lorem Ipsum is simply dummy text of the printing: 5 |
+----+-----------------------------------------------------+
货币:
+----+-------+-------+
| id | alias | title |
+----+-------+-------+
| 1 | JPY | JPY |
| 2 | USD | USD |
| 3 | GBP | GBP |
+----+-------+-------+
product_price:
+------------+-------------+-------------+
| product_id | currency_id | price |
+------------+-------------+-------------+
| 1 | 1 | 3600000.000 |
| 1 | 2 | 160.000 |
| 2 | 1 | 3260000.000 |
+------------+-------------+-------------+
我想获取特殊产品的价格,如果表product_price包含产品价格,则在使用内部联接时很容易。但是,如果表product_price不包含产品价格,我想得到结果。
例如: 在站点上,用户选择“ JPY”,因此我可以显示价格为3600000.000的产品1。 但是当用户切换到“ GBP”时,由于没有价格,因此无法显示产品1。
我同时使用了左联接,左外部联接和交叉联接,但无法获得正确的结果。 用户为产品1选择“ GBP”时,我的预期结果是:
+----+-----------------------------------------------------+-------------+----------------+-------+
| id | title | currency_id | currency_alias | price |
+----+-----------------------------------------------------+--------------------------------------|
| 1 | Lorem Ipsum is simply dummy text of the printing: 1 | 3 | GBP | NULL |
+----+-----------------------------------------------------+-------------+----------------+-------+
请帮助我,谢谢!
答案 0 :(得分:2)
嗯。认为您只想要left join
:
select p.*, c.alias, pp.price
from product p left join
product_price pp
on pp.product_id = p.id left join
currency c
on pp.currency_id = c.id and c.alias = 'JPY';
这将返回所有价格为JPY的商品(如果有)。
答案 1 :(得分:1)
您将必须使用CROSS JOIN
生成产品和货币之间的所有可能组合。然后,您可以将这些组合用作派生表,并对联结表进行LEFT JOIN
:
SELECT
dt.*, pp.price
FROM
(
SELECT
p.id AS product_id,
p.title AS product_tile,
c.id AS currency_id,
c.alias AS currency_alias,
c.title AS currency_title
FROM product AS p
CROSS JOIN currency AS c
) AS dt
LEFT JOIN product_price AS pp
ON pp.product_id = dt.product_id AND
pp.currency_id = dt.currency_id
WHERE dt.currency_title = 'GBP' -- You can provide currency filter here