【问题标题】:Union query with different numbers of columns具有不同列数的联合查询
【发布时间】:2012-12-06 18:41:42
【问题描述】:

这肯定是一个简单的问题,但我无法修复 MySQL 查询: 我想在准备好的查询下面运行

select id from table1 where c_id = :c_id 
union 
select id,name from table2 where c_id = :c_id and temp = :temp

所以我在每个表选择的输出中有不同数量的列。这是它不工作的原因吗?

【问题讨论】:

    标签: mysql select union


    【解决方案1】:

    您可以在第一个查询中SELECT 一个文字值,如下所示:

    SELECT id, 'no name' AS "name" FROM table1 WHERE c_id = :c_id
    UNION ALL
    SELECT id, name                FROM table2 WHERE c_id = :c_id 
                                                 AND temp = :temp;
    

    【讨论】:

    • @user1611830 - 不,你应该把它直接放在sql查询字符串中,不带参数,因为它是一个像常量字符串值一样的文字值。把它和qutes放在一起。
    • 事实上,我的帖子是为了简化这个不起作用的查询:select id, 'noname' as "confirm" from table1 where c_id = :c_id union select id, 'noname' as "confirm " from table2 where c_id = :c_id union select id,confirm from table3 where c_id = :c_id and confirm =1
    • 更准确地说,如果我隔离这个查询'select id from table2 where c_id = :c_id' 有效,但这不会'select id, 'noname' as "confirm" from table2 where c_id = :c_id'
    • @user1611830 我不擅长 PHP。但是尽量在每行的末尾放一个空格,如果多行写查询,在执行之前也要打印查询,看看有什么问题。
    • 确定通过传递双引号来包裹“无名”(成为“无名”)
    猜你喜欢
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多