Error: The used SELECT statements have a different number of columns, how is fix it?

依然范特西╮ 提交于 2019-12-26 06:15:13

问题


What is causes this error? How can fix it?

$find = 'hello';
$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE "%' . $find . '%" UNION SELECT * FROM tour_foreign WHERE name LIKE "%' . $find . '%"');

Error:

A Database Error Occurred
Error Number: 1222
The used SELECT statements have a different number of columns
SELECT * FROM tour_foreign_residence WHERE name LIKE "%hello%" UNION SELECT * FROM tour_foreign WHERE name LIKE "%hello%"
Filename: D:\xampp\htdocs\system\database\DB_driver.php
Line Number: 330


回答1:


There two main rules for using UNION operator:

  1. Count and ordering retreived columns should be equal in union queries
  2. Type of data in appropriates columns must be compatible

In your case, first rule is ignored. use join operator instead




回答2:


Are you sure you need an UNION?

UNION requires that all the queries that you're uniting have the same number of columns in the SELECT clause, so you shouldn't use the *, but esplicitly write the fields you need to query. Also, the clumns need to have the same data type.




回答3:


Dont use SELECT * in your query. Instead write down the actual column names that you want the get from the database. The column names should be same from both the tables. You currently have a UNION and it looks like that tables tour_foreign_residence and tour_foreign has different columns.




回答4:


According to w3schools article about UNION operator:

Each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.



来源:https://stackoverflow.com/questions/7803705/error-the-used-select-statements-have-a-different-number-of-columns-how-is-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!