【问题标题】:mysql union different number of columnsmysql联合不同的列数
【发布时间】:2013-04-07 20:02:15
【问题描述】:

我知道联合查询必须具有相同数量的列。我正在尝试从表comments 和表strings 中获取结果,该表有多个连接。我该怎么做?我还没有测试,因为我知道我会收到不同数量的列的错误。这是我尝试合并的两个查询。

查询 1(字符串)

SELECT sub.actionid as usersub, 
                ftable.`last-time` as lastvisited, updatetable.recent as mostrecent, parent.* FROM `strings` as parent 
        LEFT JOIN subscribe sub on sub.actionid=parent.id AND sub.userid=:userid
        JOIN followers ftable on ((ftable.sid=parent.sid AND ftable.page='1') OR 
        (ftable.sid=parent.sid AND ftable.position=parent.position AND ftable.page='0') 
        OR (ftable.profile=parent.starter AND parent.guideline='1')) AND ftable.userid=:userid
        JOIN `update-recent` updatetable on 
        ((updatetable.sid=parent.sid AND updatetable.position=parent.position AND updatetable.pageid='0')
        OR (updatetable.profile=parent.starter) OR (updatetable.pageid=parent.pageid AND parent.pageid!=0))
        WHERE ftable.userid=:userid AND parent.deleted='0' GROUP BY parent.id 

查询 2(cmets)

SELECT * FROM comments WHERE viewed='0' AND (`starter-id`=:userid OR respondid=:userid)

我想按时间戳列排序结果posted(最新)ORDER BY posted DESC

如何合并这些查询?

【问题讨论】:

标签: mysql


【解决方案1】:

您可能希望将列选择为 NULL 以占用某些表中的空白空间。

表 A:(id,column1)

表 B:(id,column1,column2)

Select id, column1, null as column2 from tableA
UNION
Select id, column1, column2 from tableB

【讨论】:

    【解决方案2】:

    向列数较少的查询添加空列 (null as columnName)。在这种情况下,您应该避免使用*,以便更好地控制两个查询中的列顺序。

    【讨论】:

      【解决方案3】:

      解决这个问题的另一种非常狡猾的方法是 CONCAT_WS 列不在表之间共享,例如

      SELECT `r_id`, `r_added`, CONCAT_WS('###',`otherfield1`,`otherfield2`) as r_other FROM table1
      UNION
      SELECT `r_id`, `r_added`, CONCAT_WS('###',`otherfield3`,`otherfield4`,`otherfield5`) as r_other FROM table2
      

      然后您可以通过编程方式重建该数据,例如

      $rother = explode("###", $row['r_other']);
      

      获取此数据的方法非常糟糕,但可能会让某人无法修复。您甚至可以更改分隔符,例如#t1# #t2# 搜索字符串以检查连接数据来自哪个表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        • 2021-10-27
        • 2012-12-06
        • 2015-01-29
        • 1970-01-01
        相关资源
        最近更新 更多