mysql union different number of columns

前端 未结 3 572
轻奢々
轻奢々 2021-01-02 11:47

I know union queries have to have the same number of columns. I\'m trying to get results from the table comments and results from the table strings

相关标签:
3条回答
  • 2021-01-02 12:19

    Add empty columns (null as columnName) to the query that has fewer columns. You should avoid using * in this case, to have better control on order of columns in both queries.

    0 讨论(0)
  • 2021-01-02 12:40

    You would want to select columns as NULL to take up for the empty space in certain tables.

    Table A: (id, column1)

    Table B: (id, column1, column2)

    Select id, column1, null as column2 from tableA
    UNION
    Select id, column1, column2 from tableB
    
    0 讨论(0)
  • 2021-01-02 12:45

    Another very dodgy way to get around the issue is to CONCAT_WS columns not shared between the tables e.g.

    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
    

    You can then programmatically reconstruct that data e.g.

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

    Very bad way to get at this data but might get someone out of a fix. You could even change the separator e.g. #t1# #t2# search the string for that to workout what table the concatenated data is from.

    0 讨论(0)
提交回复
热议问题