MYSQL查询产生错误

时间:2014-03-11 03:08:54

标签: php mysql

我有3张桌子:

MEMBERS:
+------------+---------+--------+
|    user    |  pass   |  sex   |
+------------+---------+--------+
| testuser3  | qwerty  | male   |
| testuser4  | qwerty  | female |
| testuser5  | qwerty  | male   |
+------------+---------+--------+


LIKEPROFILE:
+------------+---------------+
|   user     |  ilike        |
+------------+---------------+
| testuser3  | testuser4     |
+------------+---------------+

DISLIKEPROFILE:
+------------+---------------+
|   user     |  dislike      |
+------------+---------------+
| testuser4  | testuser3     |
+------------+---------------+

在我的网站上,让我们说testuser3当前已登录,即$ user = testuser3

我想创建一个MYSQL查询,其中包含$ user以外的所有成员: 1)$ user没有'喜欢'(例如:在likeprofile表中,testuser3有'喜欢'testuser4)和2)$ user没有'不喜欢'(例如:在dislikeprofile表中,testuser4'不喜欢'testuser3) 。这就是我所拥有的,但它产生了这个错误:“操作数应该包含1列”。请帮忙!

$result = queryMysql("SELECT `user` FROM `members`
                    WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
                    AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
                    AND `user` <> '$user'")

2 个答案:

答案 0 :(得分:1)

首先,如果您尚未将密码存储在数据库中,则应该确保将密码存入哈希值。如果您使用的是PHP 5.5或更高版本,则可以使用password_hash()函数执行此操作。

关于您的查询,当前的问题是您的子查询在其选择中返回多个列; SELECT *将返回该行的所有列,但NOT IN期望它们只返回一列。

$result = queryMysql(
    "SELECT `user`
     FROM `members`
     WHERE `user` NOT IN (
         SELECT `ilike`
         FROM `likeprofile`
         WHERE user='$user'
     )
     AND `user` NOT IN (
         SELECT `dislike`
         FROM `dislikeprofile`
         WHERE user='$user'
     )
     AND `user` <> '$user'"
);

但是,子查询效率低下,因此您最好使用LEFT JOINS并为ilikedislike请求NULL结果,如下所示:

$result = queryMysql(
    "SELECT `user`
     FROM `members` AS `m`
     LEFT JOIN `likeprofile` AS `lp`
         ON `m`.`user` = `lp`.`user`
     LEFT JOIN `dislikeprofile` AS `dp`
         ON `m`.`user` = `dp`.`user`
     WHERE `lp`.`ilike` IS NULL
         AND `dp`.`dislike` IS NULL
         AND `user` != '$user'"
);

答案 1 :(得分:0)

问题是您的内部查询返回多个列。尝试:

$result = queryMysql("SELECT `user` FROM `members`
                WHERE `user` NOT IN(SELECT `ilike` FROM `likeprofile` WHERE user='$user')
                AND `user` NOT IN(SELECT `dislike` FROM `dislikeprofile` WHERE user='$user')
                AND `user` <> '$user'")