繁体   English   中英

查找表名

[英]Finding tablename

我有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;"

结果出现了。好的! 假设结果像

ID内容
13这只是一个19好的,说什么.....

在此结果中,我想找到此ID:19属于哪个表? 我可以运行循环以匹配内容,但是这样做不够快且逻辑良好。

找到特定ID的表名的任何解决方案?

如果每个表中都有相同的字段名称,则示例查询将不会按原样运行。 更不用说您正在生产笛卡尔积,因为您没有加入任何领域。

我认为您可能正在寻找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演示


只是重新阅读您的文章,如果您要查找包含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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM