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

标签 php mysql select

我有 2 张 table 。

用户可以将图书添加到 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

每个用户应该只能看到他自己添加的图书和电子书的列表(按 bookID 分组)。

我需要 user1 的输出:

titel: t1
ebookID: 1 / bla1

titel: t2
ebookID: 3 / bla3

and an output for user2:

titel: t3

titel: t1
ebookID: 2 / bla2

Right now I use 2 foreach, but the problem is, if a user added an ebook but not the book, the ebook and book both don't get displayed.

$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>";
    }
}

最佳答案

只需一条语句即可从两个表中检索数据。

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

关于php - mysql 按用户和分组从 2 个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813291/

相关文章:

mysql自定义排序

SQLite 选择哪里为空?

php - 找不到类 'App\Validator' laravel

php - mysql 中的行锁

mysql - 如何快速地在 MySQL 中的多列中进行全文搜索?

mysql动态查询执行

php - 从逗号分隔的数字字符串和带连字符的数字范围填充整数数组

php - Mysql插入问题

php - Mysql在特定日期后选择查询

mysql - 根据最大订单从 2 个不同的表中选择数据