SELECT data FROM two tables in MySQL

后端 未结 3 2176
孤城傲影
孤城傲影 2021-02-08 10:36

What I have: The next structure:

table_zero
-> id (PRIMARY with auto increment)
-> other

相关标签:
3条回答
  • 2021-02-08 11:08

    By using UNION you may get several times rows with the same ID. What about using LEFT JOIN ?

    If I've understood your question:

    SELECT table_zero.id, table_1.varchar_field, table_2.varchar_field
    FROM table_zero
      LEFT JOIN table_1 ON table_zero.id = table_1.id
      LEFT JOIN table_2 ON table_zero.id = table_2.id
    WHERE table_1.varchar_field LIKE '%str%'
      OR table_2.varchar_field LIKE '%str%'
    
    0 讨论(0)
  • 2021-02-08 11:15

    Try this

    SELECT *
    FROM 
    (
    SELECT table_zero.id AS ID, table_1.varchar_field AS field
    FROM table_zero
      JOIN table_1 ON table_zero.id = table_1.id
    WHERE table_1.varchar_field LIKE '%str%'
    UNION
    SELECT table_zero.id, table_2.varchar_field  AS field
    FROM table_zero
      JOIN table_2 ON table_zero.id = table_2.id
    ) tbl
    WHERE 
    tbl.field LIKE '%str%'
    
    0 讨论(0)
  • 2021-02-08 11:16
    SELECT table_zero.id, table_1.varchar_field, table_2.varchar_field
    FROM table_zero
      LEFT JOIN table_1 ON table_zero.id = table_1.id
      LEFT JOIN table_2 ON table_zero.id = table_2.id
    WHERE table_1.varchar_field LIKE '%str%'
      OR table_2.varchar_field LIKE '%str%'
    
    0 讨论(0)
提交回复
热议问题