简体   繁体   English

在一个查询语句中将2个表连接在一起

[英]Join 2 tables together in one query statement php

Im trying to join two tables together becouse 2 columns match and i need info from second table to display the content. 我试图将两个表连接在一起,因为2列匹配,我需要第二个表中的信息来显示内容。 When i pressing a link with ?p=1a i want content to show and this info i have on the second table but not the first one. 当我按下带有?p = 1a的链接时,我想显示内容,而我在第二个表上却没有在第一个表上显示此信息。 Where table 1 and table 2 match on column Menu. 表1和表2在“菜单”列上匹配的位置。 I have shorten down on some code/table info becouse its not relevant for this problem. 我已经缩短了一些代码/表信息,因为它与该问题无关。 im then displaying the info with mysql_fetch_assoc. 即时通讯然后使用mysql_fetch_assoc显示信息。

TABLE 1

MENU | subtitle | firstname |info

info | contact

word | woord

TABLE 2

MENU | page |

info | 1a

word | 1b

My code: 我的代码:

if(isset($_GET['p'])){
    $page = $_GET['p'];

    $find = mysqli_query("SELECT * FROM testcheck, testdoc INNER JOIN testdoc ON testcheck.Menu = testdoc.MENU AND page='$page' ");
    while($row = mysqli_fetch_assoc($find)){
        $subtitle = $row['subtitle'];
        $firstname = $row['firstname'];
        echo $firstname
    }
}

Problem is correct kinda now but only letters work fine but when i combine page='1a' for example everything stop works. 现在的问题是正确的,但是只有字母可以正常工作,但是当我组合page ='1a'时,一切都停止了。

Your syntax for the join is wrong. 您的联接语法错误。

Use: 采用:

"SELECT * FROM testcheck
INNER JOIN testdoc ON testcheck.Menu = testdoc.MENU AND page='$page'
");

Read more about LEFT JOIN and RIGHT JOIN . 阅读有关LEFT JOINRIGHT JOIN更多信息。 In your case you would need RIGHT JOIN to get data that is in second table but not in first. 在您的情况下,您将需要RIGHT JOIN来获取第二个表中的数据,而不是第一个表中的数据。

Like popovitsj suggested your syntax is also wrong. 像popovitsj一样,建议您的语法也是错误的。

Correct syntax: 正确的语法:

SELECT * FROM testcheck
INNER JOIN testdoc ON testcheck.Menu = testdoc.Menu AND page='$page'

Also note that you are using MENU upper case which is not a problem on windows but will be a problem on unix, it will give you an error Column Not Found. 另请注意,您使用的是MENU大写字母,这在Windows上不是问题,但在UNIX上将是问题,这将为您显示错误Column Not Found。

EDIT 编辑

If your table has column MENU then it should be fine. 如果您的表中有MENU列,则应该没问题。

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

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