我有 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/