我有三张桌子(product
,product_description
,product_store_description
)。
产品
此表有一行
+----------+---------------------+
|product_id| description |
+----------+---------------------+
| 1 |'regular description'|
+----------+---------------------+
PRODUCT_DESCRIPTION
此表有零行
+----------+-----------+--------+
|product_id|description|language|
+----------+-----------+--------+
product_store_description
This table has zero rows
+----------+-----------+--------+--------+
|product_id|description|language|store_id|
+----------+-----------+--------+--------+
我想为所有表.description
返回WHERE product.product_id = '1'
列。
所以在这种情况下我想要的输出是
$row = $result->fetch_assoc();
echo '<pre>';
var_dump($row);
echo '</pre>';
array (size=3)
'p_description' => string 'regular description' (length=19)
'pd_description' => string '' (length=0)
'psd_description' => string '' (length=0)
我已经尝试了很多SQL的变体,这就是目前的情况。
SELECT p.description AS p_description ,pd.description AS pd_description, psd.description AS psd_description FROM product AS p
RIGHT JOIN product_description AS pd ON(pd.product_id = p.product_id)
RIGHT JOIN product_store_description AS psd ON(psd.product_id = p.product_id)
WHERE p.product_id = '1'
AND pd.language = 'en'
AND psd.language = 'en' AND psd.store_id = 1;
返回零行
我搜索了一个让我使用RIGHT JOIN
的答案,但这并没有解决我的问题。
我已经创建了一个示例表的SQL小提琴HERE,不幸的是我还没有能够让任何人回答工作。
答案 0 :(得分:2)
如果表product
包含至少一个数据。并且您希望显示其他列NULL
或自定义字符串,如"---"
,您必须在查询中指定即使连接属性为空也要加入。因此,以下查询将为您提供数据。
SELECT
p.description AS p_description ,ifnull(pd.description,"---") AS pd_description,
ifnull(psd.description,"--") AS psd_description
FROM product AS p
LEFT JOIN Product_description AS pd ON(pd.product_id = p.product_id)
LEFT JOIN product_store_description AS psd ON(psd.product_id = p.product_id)
WHERE p.product_id = '1' AND (pd.language = 'en' or pd.language is null)
AND (psd.language = 'en' or psd.language is null) AND
(psd.store_id = 1 or psd.store_id is null);
答案 1 :(得分:0)
如果我理解正确,那么您需要LEFT join,因为产品表位于查询中联接的左侧。
左连接将返回连接运算符左侧表中的所有行,而右连接将返回连接运算符右侧表中的所有行。
答案 2 :(得分:-2)
如果您想接收一些数据,您应该执行以下查询:
SELECT
p.description AS p_description ,
pd.description AS pd_description,
psd.description AS psd_description,
pd.language as language,
psd.store_id as store_id
FROM
product AS p LEFT JOIN product_description AS pd ON(pd.product_id = p.product_id)
LEFT JOIN product_store_description AS psd ON(psd.product_id = p.product_id)
WHERE
p.product_id = '1'
但在这种情况下,您必须手动控制language和store_id的值