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

标签 mysql left-join mysql-num-rows

我加入了两个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/

相关文章:

sql - 列上的左连接不在两个表之间的关系中

MySQL - 添加列并显示每条记录

php - 带有 mysql_num_rows 的 mysql 和 php 登录页面

php - 按最高值顺序选择不同的行

php - 使用 AM 和 PM 将 MySQL 时间转换为标准时间

mysql - 加入 3 个表并按用户对电影结果进行分组

php - mysqli num_rows 不返回正确的行数 - 检查所有值

php - 如何将唯一 ID 附加到 json 数组 - OctoberCMS/Laravel

mysql - 如果表不存在,如何创建*和填充*表?

c - 如何获取行数导致 SQL (C ANSI) 中的查询?