简体   繁体   English

mysql_fetch_array和mysql_query在来自两个不同表的调用中不返回任何内容

[英]mysql_fetch_array and mysql_query return nothing on a call from two different tables

I have two tables books and users. 我有两个桌子和用户。 books has a column id and users has a column called book_id . books有一个列id而用户有一个列book_id users table is populated by info about users who bought books from the store including the column book_id which referees to the id from books table. users表由有关从商店购买书籍的用户信息组成,其中包括book_id列,该列book_id了books表中的id

My questions is, I have been trying to do this but with no success. 我的问题是,我一直在尝试这样做,但没有成功。

$query = mysql_query("SELECT * FROM books, users WHERE books.id='$id' OR users.id='$id' ");
while($row = mysql_fetch_array($query)){
    $info .= $row[0] . " " . $row[1] . "<br/>";
}
echo $info; 

Table books has some data but users is empty and I am getting nothing as an output!!! 桌簿有一些数据,但是用户为空,我没有得到任何输出!!! What am I missing?? 我想念什么?

Additional attempts: 其他尝试:

SELECT * FROM books, users WHERE books.id='$id' returns empty results SELECT * FROM books, users WHERE books.id='$id'返回空结果

SELECT * FROM books WHERE books.id='$id' returns 5 rows SELECT * FROM books WHERE books.id='$id'返回5行

You're missing the correct JOIN . 您缺少正确的JOIN

Table books has some data but users is empty and I am getting nothing as an output 桌簿有一些数据, 但用户为空 ,我没有得到任何输出

Since users table contains no records you need to use LEFT | RIGHT 由于users表不包含任何记录,因此您需要使用LEFT | RIGHT LEFT | RIGHT or FULL join to get the result set, depending on what you're trying to accomplish. LEFT | RIGHTFULL连接可获取结果集,具体取决于您要完成的工作。

Therefore try to change your query to 因此,尝试将查询更改为

SELECT * 
  FROM books b LEFT JOIN
       users u ON b.id=u.book_id
 WHERE ... 

Here is SQLFiddle 这是SQLFiddle

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

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