从同一表中选择多行

时间:2014-12-08 10:08:25

标签: php mysql

我有两个表' book '和' category '。如何在“book”表中显示所有行?请注意,类别(书籍表) cat_name(类别表)之间存在联接。

预订

id   category    title
1    2           a title here
2    2           a title here
3    1           a title here
4    Comedy      a title here
5    1           a title here
6    Horror      a title here

类别

id       cat_name   
----     -------         
1        Language
2        Kids

目前我正在使用以下sql查询,它似乎只显示具有该类别编号的行,而我希望所有数据。目前我的html表格不显示第4行和第6行。

SELECT b.id, b.title, b.category, b.author, b.isbn, b.publicationYear,
        c.cat_name
        FROM book AS b
        INNER JOIN category AS c ON b.category = c.id

我的php样本

echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['cat_name'] . '</td>';   
echo '<td>' . $row['author'] . '</td>';
echo '<td>' . $row['isbn'] . '</td>';

很新的php / mysql所以任何建议或方向都值得赞赏。

2 个答案:

答案 0 :(得分:2)

您正在执行inner join,这将仅返回匹配的项目。如果您希望左表中的所有项目都使用left join而不是

    SELECT b.id, 
           b.title, 
           b.category, 
           b.author, 
           b.isbn, 
           b.publicationYear,
           c.cat_name
    FROM book AS b
    left JOIN 
    category AS c 
    ON
    b.category = c.id

更新:

执行左连接将显示cat_namecategory

不匹配的空值

解决方法是

SELECT 
b.id, 
b.title, 
b.category, 
b.author, 
b.isbn, 
b.publicationYear,
case 
 when cast(b.category as unsigned)= 0 then b.category
 else c.cat_name 
end as cat_name 
FROM book AS b
left JOIN category AS c ON b.category = c.id

答案 1 :(得分:0)

试试这个我觉得它解决了你的问题

SELECT b.id, 
       b.title, 
       b.category, 
       b.author, 
       b.isbn, 
       b.publicationYear,
       c.cat_name
FROM book AS b , category AS c
WHERE b.category = c.id