简体   繁体   English

mariadb-左外联接

[英]mariadb - LEFT OUTER JOIN

recently have migrated a server, and I have found this "error", I had mysql as a DB, and what I wanted (I'm not an expert on SQL), was to join 2 related tables by 1:N, as an example, 最近迁移了服务器,我发现了这个“错误”,我将mysql作为数据库,而我想要的(我不是SQL方面的专家)是通过1:N连接2个相关的表,例,

Table 1: Badges_Person
Table 2: Badges

Badges is a table with the badges, and Badges_Person contains a relation like (id_badge, id_person), easy, uh? 徽章是带有徽章的表,并且Badges_Person包含一个类似(id_badge,id_person)的关系,容易吗? Well this SQL query always seemed to work fine: 好吧,这个SQL查询似乎总是可以正常工作:

SELECT id, nombre, descripcion, insignias.time, obtained
FROM insignias LEFT OUTER JOIN 
     (SELECT *, '1' as obtained
      FROM insignias_user
      WHERE insignias_user.username = 'Octal'
    ) as insignias_user_seleccionado
    ON insignias.id = insignias_user_seleccionado.id_insignia;

The output of this query was the list of badges with a 'obtained' column (0 or 1) which says if the user 'Octal' has that badge or not. 该查询的输出是带有“获得”列(0或1)的徽章列表,该列表明用户“八度”是否具有该徽章。

So..., now, I have mariadb as DB, and it returns a different output, where all the rows are being marked with 'obtained' = 1. 所以...,现在,我将mariadb作为数据库,它返回一个不同的输出,其中所有行都标记为“获得” = 1。

I came here because as far as I have tried I have discarded all the silly posible errors. 我之所以来到这里,是因为据我所知,我已经放弃了所有可能的愚蠢错误。

I cannot speak to why the query is not working. 我无法说出查询为什么不起作用。 That would seem to be a data issue -- all the rows match. 这似乎是一个数据问题-所有行都匹配。

But, there is a better way to write the query: 但是,有一种更好的方式来编写查询:

SELECT i.id, i.nombre, i.descripcion, i.time, ius.obtained
FROM insignias i LEFT OUTER JOIN 
     insignias_user iu
    ON i.id = ius.id_insignia AND ius.username = 'Octal';

This is much more efficient because the intermediate table does not need to be materialized and the database can make use of appropriate indexes on insgnias_user . 这是非常有效的,因为不需要实现中间表,并且数据库可以使用insgnias_user上的适当索引。

Also note: I changed the column references to qualified column names. 另请注意:我将列引用更改为合格的列名称。 The table alias may not be correct. 表别名可能不正确。

SELECT i.id, i.nombre, i.descripcion, i.time, IF(ius.id_insignia IS NULL, 0, 1)
FROM insignias i LEFT OUTER JOIN insignias_user ius
ON i.id = ius.id_insignia AND ius.username = 'Octal';

Ok, it works again, thank you. 好的,它再次起作用,谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM