此查询有什么问题?
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`
用户表
+------------------------------------------+
| id | firstname | lastname | .... |
| 1 | Nedim | Kanat | .... |
+------------------------------------------+
朋友表
+-------------------------------------------+
| id | user_id | friend_id | .... |
| 1 | 1 | 2 | .... |
+-------------------------------------------+
答案 0 :(得分:1)
您不应该使用UNION
。您应该以这种方式使用查询:
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%'
<强>差分强>
UNION
用于添加新行。, () AS Column
用于添加为同一行中的另一列。答案 1 :(得分:1)
联合是集之间的数学运算。 这种操作要求两个表是COMPATIBLE,这意味着它们必须在数量和类型上具有相同的列。 显而易见的是,您正在尝试在3列SELECT和1列SELECT语句之间建立联合(LEFT JOIN不会像您期望的那样添加其他2列导致SELECT项目加入后的表格)