php - MySQL 排序问题

标签 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 作为 id,users.username 作为用户名,profile.defaultpictureid 作为用户图片,userprofiles 作为配置文件 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"}]

最佳答案

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

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

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

关于php - MySQL 排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792176/

相关文章:

hibernate - 如何使用 Hibernate Criteria 添加复杂的订单?

PHP 和 MySQL : Import CSV using Column Value as table

MySQL 数据库为什么 Õ 在搜索时返回为 O

php - 从表中检索主键数据

mysql - 使用数据库导出保存的 MySQL 查询?

sql-server - OrderBy 中忽略别名

php - 字体系列在 php 中不起作用

php - 分别使用带有通配符的 JQuery

php - jsonp、json、jquery、ajax 和 wordpress 刷新页面! :S

SQL LIKE,如何按加权出现次数对结果排序?