douwei8295 2015-12-08 16:43
浏览 52
已采纳

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

I want to search a product detail from multiple sql table. 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)

id | name | cast | detail | date

I tried:

Method 1:

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

Method 2:

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

Method 3:

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

1条回答 默认 最新

  • duanke3985 2015-12-08 17:03
    关注

    Note, credit really goes to Giorgos's comment at the top, I just formalized it.

    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.

    The SQL should be

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

    Just chain UNIONs till you've combined all tables.

    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.

    In that situation, the trick is to chain UNIONs on SELECTs instead of inside the FROM like so:

    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 ( ... ).

    Side note, directly inserting a variable into your SQL is potentially an SQL Injection risk. If $name is not 100% server-controlled, you may want to investigate switching to parametrized queries instead, potentially with stored procedures.

    Or just sanitize the variable. That also works. Injection was blockable that way before parametrization came along.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题