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

时间:2011-07-30 07:59:12

标签: php sql

我想使用第一个查询结果从第二个查询中获取数据。但我无法想要的是从第一个查询获取id并使用我得到的id获取内容。

我的第一个查询

$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)或死(mysqli_error($ link));

                            $row = mysqli_fetch_array($result);

第二次查询

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));
                            }

我知道它有些错误,但是现在我似乎无法想象我该怎么做才想知道我是否支持使用嵌套查询。

编辑:继承我的嵌套查询

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

我得到一个“操作数应该包含1列错误”tho

1 个答案:

答案 0 :(得分:3)

您只需要一个查询,将书籍表加入购物车表即可获取每本书的信息。

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