我需要用一个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新手,似乎无法同时比较不同行的值。
有人知道这是否是正确的方法吗?
谢谢!
答案 0 :(得分:-1)
我已编辑过这个,因为草莓写道,需要汇总一些内容,这对您的数据无效。以下解决方案有效。它与你以前做的非常相似,只不过它包含在一个子查询中。我已经测试了这个并且正常工作
WHERE CustomerName LIKE 'a_%_%'
你的calcDist函数应该有希望做类似的事情
SELECT * FROM
(SELECT DISTINCT
x.USER_ID,
n.value as name,
b.VALUE as bought,
l.VALUE as logged,
s.VALUE as `status`,
lt.VALUE as lat,
ln.VALUE as lon
FROM testing x
LEFT JOIN testing n
ON x.USER_ID = n.USER_ID and n.FIELD_ID = 2
LEFT JOIN testing b
ON x.USER_ID = b.USER_ID and b.FIELD_ID = 3
LEFT JOIN testing l
ON x.USER_ID = l.USER_ID and l.FIELD_ID = 4
LEFT JOIN testing s
ON x.USER_ID = s.USER_ID and s.FIELD_ID = 5
LEFT JOIN testing lt
ON x.USER_ID = lt.USER_ID and lt.FIELD_ID = 6
LEFT JOIN testing ln
ON x.USER_ID = ln.USER_ID and ln.FIELD_ID = 7
)tbl
WHERE tbl.logged = 'loggedin'
AND tbl.status IN ('idle', 'busy')
AND tbl.bought = 'books'
AND calcDist(12.3,13.3, tbl.lat, tbl.lon) > 5