MySQL订单按问题

时间:2011-04-26 14:51:49

标签: php mysql sql-order-by row

我想简单的问题,但是无法弄清楚如何以我想要的方式列出mysql sql。

基本上在一行中我有CityID我希望能够拿出那个== 14的CityID并将它们显示在返回的顶部(但不是作为计数)

例如

珀斯== 15 墨尔本== 14 普雷斯顿== 14 悉尼== 13

目前他们就是这样表现出来的 悉尼== 13 珀斯== 15 墨尔本== 14 普雷斯顿== 14

我的代码

$sth = mysql_query("SELECT users.id as id, users.username as username, profile.defaultpictureid as picture FROM users, userprofiles as profile WHERE online = '1' AND profile.country = ".$this->country." AND profile.state = ".$this->state." AND profile.city = ".$this->city." ORDER BY if (profile.city = 12276,0,1)");

上面的代码现在似乎正在运作。

然而,似乎也打印出两次数据。

[{ “ID”: “7”, “用户名”: “A”, “图片”: “0”},{ “ID”: “1”, “用户名”: “B”, “图片” : “0”},{ “ID”: “1”, “用户名”: “B”, “图片”: “1”},{ “ID”: “7”, “用户名”: “A”,”图片 “:” 1" }]

2 个答案:

答案 0 :(得分:2)

你从两个表(用户和个人资料)中进行选择,但是在你的where子句中没有指定任何关系,所以你得到的是两者的笛卡尔积,这就是为什么你'重新获得重复的结果。

我猜你的查询应该看起来像这样:

SELECT users.id as id, users.username as username, profile.defaultpictureid as picture
FROM users, userprofiles as profile
WHERE
    online = 1 AND
    profile.country = {$this->country} AND
    profile.state = {$this->state} AND
    profile.city = {$this->city} AND 
    users.id = userprofiles.userid     <---the join condition for the two tables
ORDER BY if (CityID = 14, 1, 0), profile.city

答案 1 :(得分:0)

您可以在排序

中应用if子句
order by if(CityID = 14,0,1)