How to get query data using result from another query?
i wanted to get the data from my second query using the first query result. But i cant What i wanted is to get id from the first query and get content using the id i got.
My 1st query
$query = "SELECT book_id , title, SUM(quantity) AS total_sales FROM shopping_cart GROUP BY title ORDER BY total_sales DESC ";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$row = mysqli_fetch_array($result);
2nd query
for ($rcount = 0; $rcount < count($row); $rcount++) {
$wanted_id = $result[$rcount]['book_id'];
$query1 = "SELECT * FROM books where id ='$wanted_id' ";
$result1 = mysqli_query($link, $query) or die(mysqli_error($link));
}
i kno开发者_运维知识库w theres somethign wrong with it but right now i cant seem to figure what how do i do it was wondering if im suppouse to use nested queries.
EDIT: heres my nested query
$query = "SELECT * from books where id IN (SELECT book_id AS id, title, SUM(quantity) AS total_sales FROM shopping_cart GROUP BY title ORDER BY total_sales DESC )";
i got a "operand should contain 1 column error" tho
You only need one query, join the books table to your shopping cart table to get the info about each book.
SELECT
books.*,
shopping_cart.book_id,
shopping_cart.title,
SUM(shopping_cart.quantity) AS total_sales
FROM
shopping_cart
INNER JOIN
books
ON
shopping_cart.book_id = books.id
GROUP BY
shopping_cart.title
ORDER BY
total_sales DESC
精彩评论