mysql按用户和分组从2个表中选择

时间:2016-08-07 10:41:04

标签: php mysql select

我有2张桌子。

用户可以将书籍添加到table_1。

bookID  titel   addedby
1       t1      user1
2       t2      user1
3       t3      user2

用户可以选择table_1中已有的图书,并将电子书添加到table_2。 他们可以选择table_1中的每个bookID,以及其他用户添加的图书。

ebookID bookID  content addedby
1       1       bla1    user1
2       1       bla2    user2
3       2       bla3    user1

每个用户都应该只看到他自己添加的书籍列表和按书签ID分组的电子书。

我需要user1的输出:

titel: t1
ebookID: 1 / bla1

titel: t2
ebookID: 3 / bla3

和user2的输出:

titel: t3

titel: t1
ebookID: 2 / bla2

现在我使用2个foreach,但问题是,如果用户添加了电子书而不是书籍,则电子书和书籍都不会显示。

$cur_user_id = wp_get_current_user()->ID;
$results = $wpdb->get_results("SELECT * FROM table_1 WHERE addedby = $cur_user_id ORDER BY title ASC");
foreach($results as $r) {
    echo '<a href="/edit-book/?id=' .$r->ID. '">' .$r->Titel. '<br>';
    $bookID = $r->ID;
    $fass = $wpdb->get_results("SELECT * FROM table_2 WHERE bookID = $bookID AND addedby = $cur_user_id ORDER by ebookID ASC");
    foreach($fass as $h) {
        echo "<a href=" .$h->ebookID. ">" .$h->content. "<br><br>";
    }
}

1 个答案:

答案 0 :(得分:1)

您只能通过一个语句从两个表中检索数据。

select table_1.title1,table_2.ebookid,table_2.content from table_1 
inner join table_2 on table_1.bookid=table_2.bookid
where table_1.addedby=$cur_user_id or table_2.addedby=$cur_user_id
相关问题