【问题标题】:How to get query data using result from another query?如何使用另一个查询的结果获取查询数据?
【发布时间】:2011-10-16 10:48:33
【问题描述】:

我想使用第一个查询结果从我的第二个查询中获取数据。但我不能我想要的是从第一个查询中获取 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) or die(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 列错误”但是

【问题讨论】:

  • 不应该是$wanted_id = $row[$rcount]['book_id']吗?
  • 另外,我相信您需要使用UNION 进行多项选择。
  • 我没有组合 2 个结果,而是我的第一个查询 where 子句假设从第二个查询中获取其条件

标签: php sql


【解决方案1】:

您只需要一个查询,将书籍表连接到您的购物车表即可获取有关每本书的信息。

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

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2011-12-02
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    相关资源
    最近更新 更多