简体   繁体   中英

Mysql query noobie assistance

Hello i hired a coder to do most my sites work. But i would like to be able to do some basic things i tried to use mysql query builder but still cant get the concept lol. so its probably really basic but i have two tables.

$sql  = "SELECT distinct count(title) FROM #cookingbooks ";
$db->setQuery($sql);
$cooking= $db->loadResult();
//var_dump($cooking);die;


$sql  = "SELECT distinct count(title) FROM #historybooks ";
$db->setQuery($sql);
$history= $db->loadResult();
//var_dump($history);die;

now either one of them will get me a count of the records, but this is where i struggle. How can i make one query to count the records from both tables and give me the total from both tables ? as one So instead of having 12,000 books for cooking. and 38,000 for history. i would just get 50,000 as my result

You can do that, but you will still need multiple queries to do that. It may be simpler to add a the 2 numbers together in php, but here you go:

select (SELECT count(title) FROM #cookingbooks)
     + (SELECT count(title) FROM #historybooks) as total_books

You may want to reconsider yor database structure and have a single books table with a type field, where the type field can identify if the book is about history or cooking. Or have a more complex tagging system by adding a tags and a tag_of_books table, where a single book can belong to multiple categories. Eg a book called "History of Cooking" can belong to both categories.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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