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.

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路