具有相同 id 但不同行名称的多行

Multiple rows with same id but different row names

我有两个包含不同列数和列名的表。

标签 a:

ID   nome       cognome    messaggio  testo      orario     ip
---  ---------  ---------  ---------  ---------  ---------  ---------
1    a          a          a          a          a          127  
2    b          b          b          b          b          111
3    a          a          tt         qqq        h          127     

选项卡 b:

id   nome       cognome    email
---  ---------  ---------  ---------
1    t          t          t

我想在两个表中都使用 %t% 并像我一样正确发布两个表的所有列?

打印:

ID   nome       cognome    messaggio  testo      orario     ip         email
---  ---------  ---------  ---------  ---------  ---------  ---------  ---------
1    t          t          null       null       null       null       t
3    a          a          tt         qqq        h          127        null

您正在寻找这样的东西:

    SELECT ID as id, nome, cognome, messaggio, testo, orario, ip, NULL AS email 
      FROM `tabA` 
     WHERE nome LIKE '%t%' OR cognome LIKE '%t%'  OR messaggio LIKE '%t%'  OR testo LIKE '%t%'

 UNION ALL

    SELECT id as id, nome, cognome, NULL as messaggio, NULL AS testo, NULL as orario, NULL AS ip, email 
      FROM `tabB` 
     WHERE nome LIKE '%t%' OR cognome LIKE '%t%'  OR email LIKE '%t%'

sqlFiddle demo

UNION 用于将多个 SELECT 语句的结果组合成一个结果集。 UNION 删除重复行,UNION ALL returns 所有行。每个SELECT语句的列号必须相等,所以我在每个SELECT中指定了所有字段,为不存在的列设置Null

请注意以上使用LIKE会严重影响性能。


  • 阅读更多关于 UNION