简体   繁体   English

如何使用另一个查询的结果获取查询数据?

[英]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. 但是我不能我想要的是从第一个查询中获取ID并使用我获得的ID获取内容。

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)); $ result = mysqli_query($ link,$ query)或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 know 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 我收到“操作数应包含1列错误”的信息

You only need one query, join the books table to your shopping cart table to get the info about each book. 您只需要一个查询,将books表加入购物车表即可获取有关每本书的信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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