简体   繁体   English

SQL SELECT 语句 - 不同的列数

[英]SQL SELECT statements - different number of columns

What's wrong with this query?这个查询有什么问题?

sql error: #1222 - The used SELECT statements have a different number of columns
SELECT `id`,`firstname`,`lastname` FROM `users` WHERE `firstname` LIKE 
'%ned%' OR `lastname` LIKE '%ned%' 
OR CONCAT(`firstname`," ", `lastname`) LIKE '%ned%' 
OR CONCAT(`lastname`," ", `firstname`) LIKE '%ned%' 
UNION SELECT `users`.`id` FROM `users` LEFT JOIN `friends` ON `users`.`id`=`friends`.`user_id`

Users table用户表

+------------------------------------------+
|   id   |  firstname | lastname | ....    |
|   1    |   Nedim    |  Kanat   |  ....   |
+------------------------------------------+

Friends table朋友桌

+-------------------------------------------+
|   id   |  user_id   | friend_id | ....    |
|   1    |   1        |  2        |  ....   |
+-------------------------------------------+

You shouldn't use UNION for this.您不应该为此使用UNION You should be using the query this way:您应该这样使用查询:

SELECT `id`,`firstname`,`lastname`, (
    SELECT `users`.`id` FROM `users` LEFT JOIN `friends` ON `users`.`id`=`friends`.`user_id`
) AS `UserID` FROM `users` WHERE `firstname` LIKE 
'%ned%' OR `lastname` LIKE '%ned%' 
OR CONCAT(`firstname`," ", `lastname`) LIKE '%ned%' 
OR CONCAT(`lastname`," ", `firstname`) LIKE '%ned%'

Difference区别

  • UNION is for adding as a new row. UNION用于添加为新行。
  • , () AS Column is for adding as another column in the same row. , () AS Column用于在同一行中添加为另一列。

An union is a mathematical operation between sets.联合是集合之间的数学运算。 This kind of operations requires the two tables to be COMPATIBLE, which means that they have to have the same columns in number and types.这种操作要求两个表兼容,这意味着它们必须具有相同的列数和类型。 And it's clearly obvious that you're trying to make an union between a 3 columns SELECT and 1 column SELECT statements (the LEFT JOIN isn't adding other 2 columns as you expect cause the SELECT projects the table after the join is made)很明显,您正在尝试在 3 列 SELECT 和 1 列 SELECT 语句之间建立联合(LEFT JOIN 没有像您预期的那样添加其他 2 列,因为 SELECT 会在进行连接后投影表)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM