【发布时间】:2017-07-06 03:56:49
【问题描述】:
我需要用一个 mySql 语句来做一个复杂的 mySQL 查询,我有一个这样的表,每个用户的数据分布在不同的行中
ID USER_ID FIELD_ID VALUE
1 1 2 my name is paul smith
2 1 3 books
3 1 4 loggedin
4 1 5 busy
5 1 6 lat
6 1 7 lon
7 2 2 my name is big boy
8 2 3 pens
9 2 4 offline
10 2 5 idle
11 2 6 lat
12 2 7 lon
每一行包含同一个user_id的不同数据
FIELD_ID=2 contains the user name
FIELD_ID=3 contains what they bought
FIELD_ID=4 logged in or offline
FIELD_ID=5 is busy or idle
FIELD_ID=6 is their latitude
FIELD_ID=7 is their longitude
我需要一个 MySQL 语句,它会返回所有已登录且状态为空闲且已购买图书且距离例如 5 英里以内的用户。
所以有四件事必须同时为真:
1. user has to be LOGGED IN
2. user has to be idle
3. user has to have bought books
4. user has to be within 5 miles of the office (located at lat=12.3, lon=13.3)
所以我从这个开始(做了上面四件事中的三件事)
SELECT distinct a.*
FROM table a
inner join table b on a.user_id = b.user_id and b.field_id = 5 and b.value='idle'
inner join table c on a.user_id = c.user_id and c.field_id = 4 and c.value = 'loggedin'
where a.field_id=3 and a.value='BOOK'
我是一个 mysql 新手,似乎上面的语句创建了三个虚拟表并将它们组合起来进行查询,所以我想再创建两个虚拟表(一个用于 lat,另一个用于 long),并将其与我现有的mySQL 函数 calcDist(lat1,lon1,lat2,lon2) 计算 2 个 gps 点之间的距离,如下所示:
SELECT distinct a.*
FROM table a
inner join table b on a.user_id = b.user_id and b.field_id = 5 and b.value='idle'
inner join table c on a.user_id = c.user_id and c.field_id = 4 and c.value = 'loggedin'
inner join table d on a.user_id = d.user_id and d.field_id = 6
inner join table e on a.user_id = e.user_id and e.field_id = 7
where a.field_id=3 and a.value='BOOK' and calcDist(12.3,13.3,d.value,e.value)<5.0;
我添加了两行(d和e)并修改了最后一行,其余相同。
对不起,我是一个真正的 mysql 新手,似乎无法同时比较不同行的值。
有人知道这是否是正确的方法吗?
谢谢!
【问题讨论】:
标签: mysql