【问题标题】:How do you join two tables but include all rows even if blank or null?你如何连接两个表,但包括所有行,即使是空白或空?
【发布时间】:2018-08-02 11:44:19
【问题描述】:

我有两张桌子。我想组合它们,但包括不返回值的行。这个问题可能会被标记为重复或其他内容,但我已经尝试阅读其他帖子但仍然失败。所以我可能低于一般的 MySQL 程序员。希望有人能帮忙。

table_price_list

item_id price_type_id   price_amount
1       1               100.00
1       2               95.00
1       3               90.00
1       4               85.00
1       5               80.00
1       6               75.00
2       1               201.56
2       2               196.45
2       3               191.78
2       4               186.36
3       1               1210.12
3       2               1205.45
3       3               1200.69
3       4               1195.48
3       5               1190.98

table_price_type

price_type_id   price_type
1               srp
2               reseller
3               distributor
4               mega
5               depot
6               special

期望的输出

item_id price_type_id   price_type
1       srp             100.00
1       reseller        95.00
1       distributor     90.00
1       mega            85.00
1       depot           80.00
1       special         75.00
2       srp             201.56
2       reseller        196.45
2       distributor     191.78
2       mega            186.36
2       depot           null
2       special         null
3       srp             1210.12
3       reseller        1205.45
3       distributor     1200.69
3       mega            1195.48
3       depot           1190.98
3       special         null

到目前为止我能得到的最好的就是这个,这留下了空白price_type

 select b.item_id, a.price_type, b.price_amount
    from table_price_type A
    left outer join table_price_list B on A.price_type_id=B.price_type_id

它不必为空,它可以是空白('')。

【问题讨论】:

  • 为什么item_ids一样? id 应该是唯一的。价格类型列具有字符串,而不是值,就像在所需的输出中一样。您是否尝试过简单的左连接? (没有“外部”?)。你的两个表同名?
  • 你想用任何特定的字符串替换null吗(在你的情况下是空格)?
  • @kry item_ids 在另一个包含所有项目的表中是唯一的。我认为不需要它,所以我没有在这里发布。您正在查看的表有 2 个主键。 item_id 和 price_type。对不起,这两个表具有相同的名称,这是一个错字。已编辑。
  • @WASEEM 它可以是null 或者它可以是空白的。只要它包含在所需的输出中。

标签: mysql


【解决方案1】:

您可以使用左连接来获得所需的结果。

select b.item_id, a.price_type, b.price_amount
from table_price_type A
left join table_price_list B on A.price_type_id=B.price_type_id

【讨论】:

  • 抱歉,但输出中忽略了空白/空的 price_type。
  • 因为您的 price_list 表中没有“null”值。我认为您想要完整的外部联接:stackoverflow.com/questions/7978663/mysql-full-join
  • 我明白了...感谢您的参考。我将尝试使用 union all 看看我可以用伪 FULL JOIN 做什么。
猜你喜欢
  • 2018-04-03
  • 2013-01-22
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多