简体   繁体   English

从同一表中选择多行

[英]Select Multiple Rows From Same Table

I have two tables ' book ' and ' category '. 我有两个表“ book ”和“ category ”。 How can I display all the rows from my 'book' table? 如何显示“书”表中的所有行? Note, there is a join between category(book table) and cat_name(category table ). 注意, category(书表)cat_name(category表 )之间存在联接

book table 书桌

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

category table 类别

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

Currently I am using the following sql query, it only seems to display rows that have a number for the category, whereas I want all the data. 当前,我正在使用以下sql查询,它似乎仅显示具有类别编号的行,而我想要所有数据。 Currently my html table doesn't display rows 4 and 6. 目前,我的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

Sample of my php 我的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>';

Quite new to php/mysql so any advice or direction is appreciated. 对php / mysql来说是相当新的,因此任何建议或指导都值得赞赏。

You are doing inner join and this will return only matching item. 您正在执行inner join ,这将仅返回匹配项。 If you want all item from left table use left join instead 如果您希望左表中的所有项目使用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

UPDATE : 更新:

Doing left join will show null for the cat_name where it does not match with the category table 如果左cat_namecategory表不匹配,则cat_name显示为null

Work around would be as 解决方法是

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

try with this i think it solved your problem 尝试与此,我认为它解决了您的问题

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

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

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