gpt4 book ai didi

MySQL- Left Join 显示比预期更多的行

转载 作者:行者123 更新时间:2023-11-30 23:29:50 27 4
gpt4 key购买 nike

我加入了两个SELECTS。第一个检索:

t1
id value
1 149
2 149
3 149
4 149

第二个:

t2 
id value
149 2
149 13
149 145
149 149

因此,我将在 t1.value = t2.id 上加入 t1/t2。但结果如下:

1   149 2
1 149 13
1 149 145
1 149 149
2 149 2
2 149 13
2 149 145
2 149 149
3 149 2
3 149 13
3 149 145
3 149 149
4 149 2
4 149 13
4 149 145
4 149 149

当期望的结果应该是这样的:

1   149   2
2 149 13
3 149 145
4 149 149

我认为出现问题是因为这是 SELECT 而不是表格。经过大量谷歌搜索后,我找不到任何解决方案。

编辑:MySQL 查询:

SELECT t1.id_sequence,t2.id_category, t2.tree
FROM
(
SELECT * FROM (SELECT 1 AS id_sequence UNION SELECT 2 AS id_sequence UNION SELECT 3 AS id_sequence UNION SELECT 4 AS id_sequence ) as tbl1
CROSS JOIN (SELECT DISTINCT id_catalog_category AS 'id_category' from catalog_category where id_catalog_category = 149) as tbl2
) as t1
LEFT JOIN
(
SELECT child.id_catalog_category AS id_category, ancestor.id_catalog_category AS tree
FROM catalog_category AS child
JOIN catalog_category AS ancestor
ON (child.lft BETWEEN ancestor.lft AND ancestor.rgt)
WHERE child.id_catalog_category = 149 AND ancestor.id_catalog_category != 1
) as t2
ON t1.id_category = t2.id_category

分别选择检索到的table1和table2。

最佳答案

Mysql join ROWS based on VALUES,这和join only VALUES不同

在你的数据集中,应该有 4*4 行返回,这正是你得到的,所以你的查询没有问题。你的期望是错误的。

例如:

t1 的第一行:1 149您可以自己看到您的联接匹配 t2 的所有行,因此返回了 4 行。这对于 t1 的所有下一行都是相同的,总共返回其中的 16 行。

编辑:检查这个:

SELECT @rownum:=@rownum+1 as `id`, t2.* 
FROM (
SELECT child.id_catalog_category AS id_category, ancestor.id_catalog_category AS tree
FROM catalog_category AS child
JOIN catalog_category AS ancestor
ON (child.lft BETWEEN ancestor.lft AND ancestor.rgt)
WHERE child.id_catalog_category = 149 AND ancestor.id_catalog_category != 1
) as t2

关于MySQL- Left Join 显示比预期更多的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11316315/

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