简体   繁体   English

在多个SQL表中选择一个名称

[英]Select a name in multiple sql table

I want to search a product detail from multiple sql table. 我想从多个SQL表中搜索产品详细信息。 I used these queries which do not work. 我使用了这些无效的查询。 I found many post about this topic but I cannot apply any of them. 我找到了许多有关该主题的帖子,但我无法应用其中任何一个。

Every table has the same structure like (I have 14 table in this category) 每个表都具有相同的结构(我在这个类别中有14个表)

id | name | cast | detail | date

I tried: 我试过了:

Method 1: 方法1:

$result = mysqli_query($db,"SELECT movie.*, audio.* 
  FROM movie,audio WHERE movie.name='$name' OR audio.name='$name'");

Method 2: 方法2:

$result = mysqli_query($db,"SELECT * 
  FROM movie,audio WHERE movie.name='$name' OR audio.name='$name'");

Method 3: 方法3:

$result = mysqli_query($db,"SELECT * FROM movie,audio WHERE name='$name'");

Note, credit really goes to Giorgos's comment at the top, I just formalized it. 请注意,信誉确实是Giorgos在顶部的评论,我只是将其正式化。

Assuming all tables line up perfectly, and you're just trying to look up something with name in all tables, your third attempt is really close. 假设所有表都完美地对齐,并且您只是想在所有表中查找带有name东西,那么您的第三次尝试实际上已经结束。

The SQL should be SQL应该是

SELECT *
FROM movie
    UNION audio
WHERE name='$name'

Just chain UNION s till you've combined all tables. 只需链接UNION直到您合并了所有表格。

Only catch is that the columns will be labeled in the way Movie has them, and if there's any structural differences between the tables, you'll get a lot of weirdness and not the results you want. 唯一要注意的是,这些列将按照Movie拥有它们的方式进行标记,并且如果表之间存在任何结构差异,您会感到很奇怪,而不是想要的结果。

In that situation, the trick is to chain UNION s on SELECT s instead of inside the FROM like so: 在这种情况下,诀窍是将UNIONSELECT而不是像这样在FROM内:

SELECT *
FROM movie
WHERE name='$name'
UNION
SELECT *
FROM audio
WHERE name='$name'

If the SQL flavor dislikes that setup, just wrap it in a SELECT * FROM ( ... ) . 如果SQL风格不喜欢该设置,只需将其包装在SELECT * FROM ( ... )

Side note, directly inserting a variable into your SQL is potentially an SQL Injection risk. 旁注,直接将变量插入SQL可能会导致SQL注入风险。 If $name is not 100% server-controlled, you may want to investigate switching to parametrized queries instead, potentially with stored procedures. 如果$name不是100%由服务器控制的,则可能需要调查切换到参数化查询的过程,可能使用存储过程。

Or just sanitize the variable. 或者只是清理变量。 That also works. 那也行。 Injection was blockable that way before parametrization came along. 在进行参数化之前,以这种方式可以阻止注入。

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

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