2013-05-04 29 views
-1

我有8個表格。假設它爲x1,x2 ... x8。 這些表格具有類似於以下字段的結構:id,content,pageview。查找表名

瀏覽量計算特定ID的瀏覽次數。帖子存儲在具有特定ID的行中。

我想根據這8個表中的綜合瀏覽量找到第一個前10位的文章。

我用:

$sql="select id,content from x1,x2,x3,x4,x5,x6,x7,x8 ORDER by pageview;" 

結果來up.ok! 假設結果是一樣

標識內容
13,這只是一個 19好該說什麼 .. .. 。

在這個結果我想找到這個ID:19屬於哪個表? 我可以運行循環來匹配內容,但是這不會足夠快和良好的邏輯..

任何解決方案來查找特定id的表名?

回答

2

如果每個表中的字段名相同,則您的示例查詢將不會按原樣運行。更不用說,你正在生產笛卡爾產品,因爲你沒有加入任何領域。

我想你可能會尋找一個替代UNION

select * 
from (
    select 'x1' as whichtable, id, content, pageview from x1 
    union 
    select 'x2' as whichtable, id, content, pageview from x2 
    ... 
    union 
    select 'x8' as whichtable, id, content, pageview from x8 
) t 
order by pageview 

然後你可以使用whichtable場看到的結果來自哪個表。

以下是樣本SQL Fiddle Demo


只是重讀您的文章,如果你正在尋找該表中包含ID 19,那麼你就可以在where子句添加到上述查詢:

select * 
from (
    select 'x1' as whichtable, id, content, pageview from x1 
    union 
    select 'x2' as whichtable, id, content, pageview from x2 
    ... 
    union 
    select 'x8' as whichtable, id, content, pageview from x8 
) t 
where id = 19 
order by pageview 
+0

@ user2320375 - 沒問題,很高興我能幫上忙! – sgeddes 2013-05-04 19:03:36