根据来自多个表的标签显示数据

时间:2021-03-31 08:53:27

标签: php mysql mysqli

我正在制作一个页面,其中数据将根据来自多个表的 #tag 值显示。 像 4 个表 Books, Articles, Authors & Categories。所有表都有不同的字段名称,但有些字段名称很常见,例如 (id, name, tags)

我正在使用以下查询,它仅显示一张表中的数据。

$tag = 'compu';
SELECT * from books WHERE tags like '%".$tag."%' order by id

请指导我如何显示来自多个表的数据,如下所示:

必填结果

<块引用>
  1. 类型:书籍(计算技巧)
  2. 类型:书籍(计算公式)
  3. 类型:文章(计算机结构)
  4. 类型:书籍(计算假货)
  5. 类型:文章(计算机零件)
  6. 类型:类别(计算)
  7. 类型:作者(Ahmad Computer Master)

文章表:

enter image description here

类别表:

enter image description here

作者表:

enter image description here

图书表:

enter image description here

1 个答案:

答案 0 :(得分:1)

您在问题中提出的架构之间存在差异。因此,让我们找出您需要哪些列。对我来说,您似乎只需要一些名字,我假设它是 aname。如果这不是你需要的数据,你可以调整下面的代码:

类别、文章、作者、书籍

select concat('Type: ', typename, '(', aname, ')')  as result
from (
    (select 'Category' as typename, aname from Categories)
    union
    (select 'Article' as typename, aname from Articles)
    union
    (select 'Author' as typename, aname from Authors)
    union
    (select 'Book' as typename, aname from Books)
) t

代码未经测试,如果有错别字,请告诉我!

循环时可以将索引添加到结果中。您应该确保保护自己和您的代码免受 SQL 注入。

相关问题