我有这个查询从两个表调用信息。
DB::get("SELECT friends. * , (SELECT `login` FROM `users` WHERE `users`.`id` = friends.`user_id`) AS `login` FROM `friends` WHERE `id_user`='" . $this->user['id'] . "' ORDER BY `id` DESC LIMIT ")
因此,如果用户在朋友列表中显示用户名,我想获得用户名和头像。头像行是avatar
。
我试着这个。
DB::get("SELECT friends. * , (SELECT `login`, `*avatar*` FROM `users` WHERE `users`.`id` = friends.`user_id`) AS `login` FROM `friends` WHERE `id_user`='" . $this->user['id'] . "' ORDER BY `id` DESC LIMIT ")
并给我错误
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
哪里出错?
答案 0 :(得分:2)
您需要使用JOIN
,例如:
SELECT f.*, u.*
FROM friends f JOIN users u ON f.user_id = u.id
WHERE f.id_user = <your_id>
ORDER BY id DESC LIMIT <your_limit>;
答案 1 :(得分:2)
首先你应该使用Prepared Statement,其次,你不能写内联视图,它有两列
SELECT friends. * , (SELECT `login`, `*avatar*` FROM ..
相反,您应该使用JOIN
,这可能比当前方法更有效且更具可读性。