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

时间:2010-09-07 04:10:25

标签: sql mysql mysql-error-1222

还有另外一个与此相似的问题,但它似乎没有回答我的问题。

我的问题是:为什么我从以下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

+------------+---------------+------+-----+---------+----------------+
| 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    |                |
+---------------+--------------------------------------+------+-----+---------+----------------+

如果你想对你在这里看到的任何疯狂事情提供任何反馈,请随时这样做。我会接受我的肿块。

1 个答案:

答案 0 :(得分:33)

UNIONs(UNIONUNION ALL)要求UNION的所有查询都有:

  1. SELECT子句中的列数相同
  2. 列数据类型必须在每个位置匹配
  3. 您的查询有:

    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表,但似乎没有使用这些信息。