2012-03-29 73 views
1

是否可以將行號作爲ID返回? 在我看來,其中i合併我的表,我不能做一個唯一的ID,因爲我需要創建左 加入到存儲的每一個值:斯芬克斯搜索結果中的行號爲id

CREATE VIEW 
sphinx 
AS 
SELECT 

company.company_id, 
company.company_name, 
company.company_keywords, 

company_address.address_street, 
company_address.address_number, 
company_address.address_telephone, 
company_address.address_fax, 
company_address.address_email, 
company_address.address_website, 
company_address.address_authorized, 

company_contact.contact_name, 
company_contact.contact_surname, 
company_contact.contact_telephone, 
company_contact.contact_mobilephone, 
company_contact.contact_fax, 
company_contact.contact_email, 

company_page.page_content, 
company_page.page_description, 
company_page.page_keywords 

FROM company 
LEFT JOIN company_address ON company.company_id = company_address.company_id 
LEFT JOIN company_page ON company.company_id = company_page.company_id 
LEFT JOIN company_contact ON company.company_id = company_contact.company_id 

當我收到的行數我可以這樣做SELECT * FROM sphinx LIMIT 1 OFFSET rowNumber 以獲取該行的信息。

謝謝你的時間。

回答

2

你可以做到這一點通過以下方式

SELECT * FROM 
(
SELECT 
(@rownum:[email protected] + 1) as rownumber, q.* 
FROM (
SELECT 
* /*shortened for readability*/ 
FROM company 
LEFT JOIN company_address ON company.company_id = company_address.company_id 
LEFT JOIN company_page ON company.company_id = company_page.company_id 
LEFT JOIN company_contact ON company.company_id = company_contact.company_id 
, (select @rownum:=0) r 
) q 
) asdf 
WHERE rownumber BETWEEN 2 AND 3 /*or whatever*/ 

編輯:要解釋一點:

這一個

, (select @rownum:=0) r 

聲明並初始化這將作爲我們ROWNUMBER變量。 如果您在最內層查詢的SELECT列表中包含@rownum,則會在每行中得到一個值爲0的列。

因此,您將此內部查詢設爲子查詢,並將@rownum變量加1。 只有這個

SELECT 
(@rownum:[email protected] + 1) as rownumber, q.* 
FROM (
SELECT 
* /*shortened for readability*/ 
FROM company 
LEFT JOIN company_address ON company.company_id = company_address.company_id 
LEFT JOIN company_page ON company.company_id = company_page.company_id 
LEFT JOIN company_contact ON company.company_id = company_contact.company_id 
, (select @rownum:=0) r 
) q 

你已經有一個rownumber。既然你不能在WHERE子句中引用列別名rownumber,你會寫類似

WHERE (@rownum:[email protected] + 1) BETWEEN 2 AND 3 /*or whatever*/ 

但是這會導致錯誤的結果,因爲@rownum變量將再次獲得增加和你ROWNUMBER會如

2 
4 
6 

等等。因此,你必須把它放在另一個子查詢中,然後你可以通過WHERE子句「限制」你的查詢。

還有其他問題?

+0

它確實有效..謝謝!你能解釋一下有什麼事嗎? – Sem 2012-03-29 12:17:37

+0

@Zundrium編輯我的答案。 – fancyPants 2012-03-29 12:55:37