SQL:如何将大量列和大量表中的特定值连接到一个查询中?

时间:2015-02-06 00:17:36

标签: mysql sql join

我在SQL上有点新手(如果在其他地方已经回答了我道歉,虽然我似乎找不到任何指甲的东西)并且在这个问题上已经被困了多年。作为前言,我已经研究和了解了各种连接和内连接等,我理解它们是如何工作的,它们似乎适用于少量数据。但是,我的问题是列的数量和表的数量是如此之大,我需要知道是否有一种更简单的方法将这些数据连接到一个查询中。

所以这就是我所拥有的:

 $query2 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase1 WHERE id IN(3,12,22)";
    $query3 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase2 WHERE id IN(3,12,22)";
    $query4 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase3 WHERE id IN(3,12,22)";
    $query5 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase4 WHERE id IN(3,12,22)";
    $query6 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase5 WHERE id IN(3,12,22)";
    $query7 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase6 WHERE id IN(3,12,22)";
    $query8 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase7 WHERE id IN(3,12,22)";
    $query9 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase8 WHERE id IN(3,12,22)";
    $query10 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase9 WHERE id IN(3,12,22)";
    $query11 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase10 WHERE id IN(3,12,22)";
    $query12 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase11 WHERE id IN(3,12,22)";
    $query13 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase12 WHERE id IN(3,12,22)";

我想将这些查询结果合并到一个查询中。我在phase1,phase2 e.t,c之间尝试了一个简单的逗号分隔,但是我抛出了一个模糊的列错误。我理解这是因为我没有添加

phase1.fen_toit

OR

phase1.tuiles

依此类推SELECT,因为这看起来非常漫长!

如果有人可以提供帮助,我将非常感激。我肯定答案是盯着我的脸!

1 个答案:

答案 0 :(得分:1)

使用UNIONUNION ALL加入您的查询,如下所示:

$query2 = "SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase1 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase2 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase3 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase4 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase5 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase6 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase7 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase8 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase9 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase10 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase11 WHERE id IN(3,12,22)
             UNION ALL
           SELECT fen_toit,tuiles,zinc,bois,bac_acier FROM phase12 WHERE id IN(3,12,22)";