2011-04-26 141 views
0

嗨簡單的問題,我猜,但無法弄清楚如何列出mysql的SQL我想要的方式。MySQL訂單問題

Basiclly一行我有CityID的我希望能夠拉出CityID的是== 14,並在返回的頂部顯示他們(但不作爲COUNT)

爲如 珀斯= = 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」,「username」:「A」,「picture」:「0」},{「id」:「1」,「username」:「B」,「picture 「:」 0 「},{」 ID 「:」 1" , 「用戶名」: 「B」, 「圖片」: 「1」},{ 「ID」: 「7」, 「用戶名」: 「A」, 「圖片報」:「1」}]

+2

向我們展示你迄今爲止查詢... – 2011-04-26 14:53:01

+0

問題似乎是其中A應== 0的profile.defaultpictureid和B應該返回1 – RussellHarrower 2011-04-26 15:17:54

回答

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 
0

您可以將一個如果排序

order by if(CityID = 14,0,1) 
+0

剛剛嘗試過,可悲的是它沒有工作這是我的代碼[code] $ 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)「); [/ code] – RussellHarrower 2011-04-26 15:07:05

+0

這個工程,但現在有一個是起訴與profile.defaultpictureid – RussellHarrower 2011-04-26 15:24:22