gpt4 book ai didi

php - 即使连接数据为空,Mysql如何返回行

转载 作者:行者123 更新时间:2023-11-28 23:39:28 25 4
gpt4 key购买 nike

我有三个表(productproduct_descriptionproduct_store_description)。

产品

这张表只有一行

+----------+---------------------+
|product_id| description |
+----------+---------------------+
| 1 |'regular description'|
+----------+---------------------+

产品描述

这个表有零行

+----------+-----------+--------+
|product_id|description|language|
+----------+-----------+--------+

product_store_description

This table has zero rows

+----------+-----------+--------+--------+
|product_id|description|language|store_id|
+----------+-----------+--------+--------+

我想返回所有表 WHERE product.product_id = '1'.description 列。

所以在这种情况下,我想要的输出是

$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 fiddle HERE的示例表,不幸的是我还没有能够让任何人回答工作。

最佳答案

如果表 product 至少包含一个数据。并且您想要显示其他列 NULL 或自定义字符串,例如 "---" 您必须在查询中指定连接,即使连接属性为 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);

关于php - 即使连接数据为空,Mysql如何返回行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34788808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com