我在我的网络应用程序上堆叠了(我想)ORDER BY问题。没有其他问题/答案似乎与我的相同或我无法应用于我的问题。我会尝试尽可能地用一个简单的案例来解释自己,这个案例也可以解决我的问题。
想象一下3个表,“客户”,“地址”和“CustomersAddress。
**Customers**
id, name, surname
1, "John", "Willis"
2, "Sarah", "Davies"
3, "Mark", "Jones"
4, "Linda", "Ede"
**Address**
id_dir, address
1, "some adress"
2, "other address"
3, "holliday address"
4, "my other house address"
5, "Flat in the beach address"
**CustomersAdress**
id_ca, id_customer, id_address
1, 1, 4
2, 2, 4
3, 3, 1
4, 1, 2
5, 2, 2
6, 4, 5
7, 4, 3
很明显,CustomersAdress是一个将客户与他们拥有的地址联系起来的表格。
通过简单的INNER JOIN,我可以得到以下所有关系:
SELECT id_customer, surname, name, id_dir, address
FROM CustomersAddress
INNER JOIN Customers ON Customers.id=CustomerAddress.id_customer
INNER JOIN Address ON Address.id_dir=CustomerAddress.id_address
有了这些,我可以订购ORDER BY,例如,如下
ORDER BY surname
甚至
ORDER BY surname, id_dir / ORDER BY surname, id_dir
使用“ORDER BY id_dir,surname”示例我会得到:
idcustomer, surname, name, id_dir, address
3, "Jones", "Mark", 1, "some address"
2, "Davies", "Sarah", 2, "other address"
1, "Willis", "John", 2, "other address"
4, "Ede", "Linda" 3, "holliday address"
2, "Davies", "Sarah", 4, "my other house address"
1, "Willis", "John", 4, "my other house address"
4, "Ede", "Linda", 5, "Flat in the beach address"
直到这里没什么新鲜的。但我正在尝试做的是嵌套订单(不知道如何命名)其中,订单将是与地址相关的姓氏以及拥有该地址的客户。
Ergo,首先查看带有第一个地址的第一个姓氏(戴维斯),然后查找具有相同地址(独立于姓氏)的客户,并获取它们(Willis),之后继续下一个客户姓氏或地址如果有来自同一客户的更多。等等。
我渴望的结果:
idcustomer, surname, name, id_dir, address
2, "Davies", "Sarah", 2, "other address"
1, "Willis", "John", 2, "other address"
2, "Davies", "Sarah", 4, "my other house address"
1, "Willis", "John", 4, "my other house address"
4, "Ede", "Linda", 3, "holliday address"
4, "Ede", "Linda", 5, "Flat in the beach address"
3, "Jones", "Mark", 1, "some address"
这甚至可以使用mysql查询吗?或者一个独特/更好的方法是进行示例查询,将其保存在数组上并使用php从那里订购?我怎样才能在两种情况下都能得到它。
我感谢任何帮助或建议!
答案 0 :(得分:1)
按所需顺序尝试订购:
ORDER BY table_one.field_A ASC table_two.field_E DESC
答案 1 :(得分:1)
你可以使用mysql的FIELD()
SELECT id_customer, surname, name, id_dir, address
FROM CustomersAddress
INNER JOIN Customers ON Customers.id=CustomersAddress.id_customer
INNER JOIN Address ON Address.id_dir=CustomersAddress.id_address
ORDER BY FIELD(id_dir, 2,4,3,5,1), surname;
SQLFiddle示例 - http://sqlfiddle.com/#!2/3ea9c/18
这将需要子查询或预查询来获取订单。
答案 2 :(得分:0)
您只需先按地址订购:
ORDER BY id_dir, surname