编辑
我建议更改您的表结构。
CREATE TABLE users_friends(
userid int,
friendid int,
primary key (userid, friendid)
);
CREATE TABLE users (
userid int primary key,
email varchar(100),
name VARCHAR (100),
index (email,name)
);
INSERT INTO users VALUES (1, 'a@g.com', 'noob'), (2,'b@g.com', 'Joe');
INSERT INTO users_friends (userId, friendId)
VALUES (2, (SELECT userId
FROM users
WHERE email = 'a@g.com'
AND name = "noob"
AND NOT exists (SELECT * FROM users_friends as uf
JOIN users as u
ON u.userid = uf.userid
where uf.friendid = 2 AND name = "noob"
)
)
);
SQL 小提琴演示
尝试这个:
<?php
function select_query ($userid,$friendname, $email){
$host = "host";
$user = "username";
$password = "password";
$database = "database name";
// open connection to databse
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
//Is someone registered at other conference from table registration
$query = " INSERT INTO users_friends (userId, friendId)
VALUES (".$userId.", (SELECT userId
FROM users
WHERE email = '".$email."'
AND name = '".$friendname."'
AND NOT exists (SELECT * FROM users_friends as uf
JOIN users as u
ON u.userid = uf.userid
where uf.friendid = ".$userId." AND name = '"$friendname"'
)
)
)";
$result = mysqli_query($link, $query);
return $query;
return $result;
}
mysqli_close($link);
}
echo select_query(1,noob,'a@g.com');
?>
就像我上面提到的,我不确定你的意思。如果您的意思是动态的,您可以更改变量的值,这可能会有所帮助。在您之前的帖子中,您使用了 PHP。所以,我的猜测是你正在使用 PHP。