Select same column from multiple tables only WHERE something = something

后端 未结 2 1105
余生分开走
余生分开走 2021-01-02 14:13

I have two tables with very similar structures.

Universidades
nombre | contenido | becas | fotos etc etc etc
Internados
nombre | todo | becas | fotos etc et         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 15:06

    most of the time a union can be achieved by doing a join:

    SELECT nombre 
      FROM internados 
    UNION 
    SELECT nombre 
      FROM universidades 
     WHERE nombre = ?
    

    would better be:

    SELECT nombre
      FROM internados i
      JOIN universidades u
        ON i.nombre = u.nombre
       AND nombre = ?
    

    which is way simpler to read. (you may also use the JOIN syntax, but I prefer plain old manual joins).

    But whether this is a union or a join, always remember that both tables get merged in the result:

    nombre | todo | becas | fotos | ... | contenido | becas | ...
    

    so basically, as you put a condition on nombre, you'll either get an empty set, or the name you've given to the query. But hthe way you've written your union, only the second set gets the where condition applied, not the first one. You shall put the condition on both of the queries of the union:

    SELECT nombre 
      FROM internados 
     WHERE nombre = ?
    UNION 
    SELECT nombre 
      FROM universidades 
     WHERE nombre = ?
    

提交回复
热议问题