这就是我的表格:
id | name | value
-----------------
1 | user1| 1
2 | user2| 1
3 | user3| 3
4 | user4| 8
5 | user5| 6
6 | user7| 4
7 | user8| 9
8 | user9| 2
我想要做的是在一个查询中选择所有其他用户,其值是user1的值低于其值加3,高于其值减去3或等于其值。
这样的事情:
$result = mysqli_query($con,"SELECT * FROM users WHERE value<'4' OR value>'-2'") or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
echo $row['name'].'<br/>';
}
问题是每次运行查询时,users1的值都会有所不同。
答案 0 :(得分:1)
抱歉蹩脚的名字,但这应该有效:
注意:我将您的数据命名为“st”。
SELECT b.user, a.value as "user1val", b.value as "otheruservalue" FROM st as a
join st as b
on a.user = "user1" and a.user != b.user
where
(b.value > (a.value - 3)) and (b.value < (a.value + 3))
我们通过连接相同的表获得user1的唯一值和其他用户的值。之后我们只是做一些简单的比较来过滤具有合适值的行。
答案 1 :(得分:0)
$user1 = mysql_fetch_assoc(mysql_query("SELECT `value` FROM `users` WHERE id='1'"));
$result = mysql_query("SELECT * FROM `users` WHERE value<'".$user1['value']."+3' OR value>'".$user1['value']."-3'");
答案 2 :(得分:0)
或嵌套查询:
$result = mysqli_query($con, "select * from `users` where `value` < (select `value` from `users` where `name`='user1')+3 OR `value` > (select `value` from `users` where `name`='user1')-3");