我知道如何从单个表中选择MySQL查询中获取顺序结果数。我从困难中解决的是从多个表中选择时如何做到这一点。
例如:
SELECT fieldA, fieldB FROM tableFoo, tableBar WHERE condition = 'true'
如何修改此项以添加结果的行号? (这可能很简单,但出于某种原因,我无法绕过该怎么做。)
答案 0 :(得分:1)
也许(未经测试):
SET @row_number:=0;
SELECT @row_number:=@row_number+1 AS row_number, A.fieldA, A.fieldB FROM
(SELECT fieldA, fieldB FROM tableFoo, tableBar WHERE condition = 'true') AS A
ORDER BY row_number;
这是一个现有数据库的匿名示例:
SQL语句:
SET @row_number:=0;
SELECT @row_number:=@row_number+1 AS row_number, A.id, A.sname, A.fname FROM
(select h.id, right(md5(m.sname), 5) sname, right(md5(m.fname), 5) fname from member m
join household h on h.id = m.household_id where h.id > 9000
order by h.id, m.sname, m.sname) as A limit 20;
结果:
1 9001 7f9f6 424d5
2 9002 5bc65 cc2c0
3 9002 5bc65 8b13a
4 9002 5bc65 addb2
5 9002 5bc65 14f57
6 9002 5bc65 95924
7 9003 5adb1 cc0e0
8 9003 5adb1 ac703
9 9003 5adb1 e2ae7
10 9003 5adb1 fe3dc
11 9003 5adb1 d5eb3
12 9003 5adb1 d24a0
13 9004 35fc7 cd978
14 9004 35fc7 41fd1
15 9005 41b5c 32fd4
16 9005 41b5c 8c1bb
17 9005 41b5c 6119a
18 9006 dd3fd 941a2
19 9007 345a4 a7d5e
20 9007 345a4 4c161