从特定用户的两个mysql表中获取数据

时间:2017-06-17 08:10:14

标签: php mysql

SELECT customer_id,created,total_price 
FROM `orders` 
UNION SELECT product_id,quantity 
FROM order_items

我的代码是从特定用户的两个mysql表中获取数据。

 Photo attached here

2 个答案:

答案 0 :(得分:0)

使用UNION时必须等于列数,如果数量为null,则可以添加IFNULL

    $query = "SELECT `product_id`, `total_price`, ‌`​‌​created`, IFNULL(`quantity`,0) FROM `order_items`
    LEFT JOIN `orders` ON `order_items`.`order_id` = `orders`.`id`
    WHERE `orders`.`customer_id`={$_SESSION['email']}");
    $order_result = mysqli_query($conn, $query);

PS:为了准确回复,请粘贴表格架构

答案 1 :(得分:0)

假设order_idorder_items表中的forein键列,您可以使用JOINCOUNT来获取所需的值,例如:

SELECT o.customer_id, o.created, o.total_price, COUNT(oi.id)
FROM orders o LEFT JOIN order_items oi ON o.id = oi.order_id
GROUP BY o.customer_id, o.created, o.total_price;