小编典典

使用的SELECT语句具有不同数量的列(REDUX !!)

mysql

那里还有另一个与此类似的问题,但似乎并没有回答 我的 问题。

我的问题是这样的:为什么我ERROR 1222 (21000): The used SELECT statements have a different number of columns要从下面的SQL中找回此错误?

SELECT * FROM friends
LEFT JOIN users AS u1 ON users.uid = friends.fid1
LEFT JOIN users AS u2 ON users.uid = friends.fid2
WHERE (friends.fid1 = 1) AND (friends.fid2 > 1)
UNION SELECT fid2 FROM friends
WHERE (friends.fid2  = 1) AND (friends.fid1 < 1)
ORDER BY RAND()
LIMIT 6;

这里是users

+------------+---------------+------+-----+---------+----------------+
| Field      | Type          | Null | Key | Default | Extra          |
+------------+---------------+------+-----+---------+----------------+
| uid        | int(11)       | NO   | PRI | NULL    | auto_increment |
| first_name | varchar(50)   | NO   |     | NULL    |                |
| last_name  | varchar(50)   | NO   |     | NULL    |                |
| email      | varchar(128)  | NO   | UNI | NULL    |                |
| mid        | varchar(40)   | NO   |     | NULL    |                |
| active     | enum('N','Y') | NO   |     | NULL    |                |
| password   | varchar(64)   | NO   |     | NULL    |                |
| sex        | enum('M','F') | YES  |     | NULL    |                |
| created    | datetime      | YES  |     | NULL    |                |
| last_login | datetime      | YES  |     | NULL    |                |
| pro        | enum('N','Y') | NO   |     | NULL    |                |
+------------+---------------+------+-----+---------+----------------+

这里是friends

+---------------+--------------------------------------+------+-----+---------+----------------+
| Field         | Type                                 | Null | Key | Default | Extra          |
+---------------+--------------------------------------+------+-----+---------+----------------+
| friendship_id | int(11)                              | NO   | MUL | NULL    | auto_increment |
| fid1          | int(11)                              | NO   | PRI | NULL    |                |
| fid2          | int(11)                              | NO   | PRI | NULL    |                |
| status        | enum('pending','accepted','ignored') | NO   |     | NULL    |                |
+---------------+--------------------------------------+------+-----+---------+----------------+

如果您也想对这里发生的任何疯狂事情提供任何反馈,请随时这样做。我会结成小块。


阅读 799

收藏
2020-05-17

共1个答案

小编典典

UNION(UNIONUNION ALL)要求所有UNION查询必须具有:

  1. SELECT子句中的列数相同
  2. 列数据类型必须在每个位置都匹配

您的查询有:

SELECT f.*, u1.*, u2.* ...
UNION 
SELECT fid2 FROM friends

我最简单的重写是:

   SELECT f.*, u.*
     FROM FRIENDS AS f
     JOIN USERS AS u ON u.uid = f.fid2
    WHERE f.fid1 = 1 
      AND f.fid2 > 1
UNION 
   SELECT f.*, u.*
     FROM FRIENDS AS f
     JOIN USERS AS u ON u.uid = f.fid1
    WHERE f.fid2  = 1 
      AND f.fid1 < 1
ORDER BY RAND()
LIMIT 6;

您已经USERS两次加入表,但似乎没有使用该信息。

2020-05-17