那里还有另一个与此类似的问题,但似乎并没有回答 我的 问题。
我的问题是这样的:为什么我ERROR 1222 (21000): The used SELECT statements have a different number of columns要从下面的SQL中找回此错误?
ERROR 1222 (21000): The used SELECT statements have a different number of columns
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:
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:
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 | | +---------------+--------------------------------------+------+-----+---------+----------------+
如果您也想对这里发生的任何疯狂事情提供任何反馈,请随时这样做。我会结成小块。
UNION(UNION和UNION ALL)要求所有UNION查询必须具有:
UNION
UNION ALL
您的查询有:
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两次加入表,但似乎没有使用该信息。
USERS