openlang

Missing field through a derived table in SQL

I'm executing the following SQL statement:

SELECT wc_order_items.order_id AS Order_Number
FROM wc_order_items
LEFT JOIN (
    SELECT meta_value AS Given_Name
    FROM wc_metadata
    WHERE meta_key = '_shipping_first_name'
) AS shipping
ON wc_order_items.order_id = shipping.post_id
WHERE wc_order_items.order_id = 3276

It produces the following error:

#1054 - Unknown column 'shipping.post_id' in 'on clause'.

This seems like fairly straightforward code, yet I can't get it working. Where have I gone wrong?

The conversation continues 2

Follow the reasoning
  1. Permalink

    Your subquery doesn't include post_id in its selection. Include that field in the subquery this way:

    SELECT wc_order_items.order_id AS Order_Number
    FROM wc_order_items
    LEFT JOIN (
        SELECT meta_value AS Given_Name, post_id -- include this
        FROM wc_metadata
        WHERE meta_key = '_shipping_first_name'
    ) AS shipping
    ON wc_order_items.order_id = shipping.post_id
    WHERE wc_order_items.order_id = 3276
  2. Permalink

    I see the solution does work and was accepted, but the query can be written much more neatly. Tried with mysql and postgres.

    SELECT orders.order_id AS Order_Number
    FROM wc_order_items AS orders
    LEFT JOIN wc_metadata AS metadata
      ON orders.order_id = metadata.post_id
     AND metadata.meta_key = '_shipping_first_name'
    WHERE orders.order_id = 3276

Other sides of the same question

  1. Testing D arrays for a matching entry

    with associative arrays this is possible how is this done with ordinary arrays? I'd like a validation expression, for example

    Replies 2Latest activity d
  2. Removing an optional column safely with PostgreSQL 9+

    I want to remove a column belonging to a table. What's the way to determine whether that column is present? I read the manual…

    Replies 2Latest activity sql
  3. Solc 0.7.0 rejects construction of my struct with a mapping member

    My npm installation provides Solc version 0.7.0. Creating a Struct with a mapping inside emits the message: "Struct containin…

    Replies 2Latest activity solidity