Friday, March 4, 2022

[FIXED] How do I combine 2 SELECT statements where the result

Issue

How do I combine 2 SELECT statements where the result of the first select is used in the WHERE of the second SELECT

Below is the code I am using right now:

$order_id = 7655;

$first  = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM wp_postmeta WHERE meta_key = '_ticket_order' AND meta_value = %d", $order_id ) );

if ( $first ) {
  $second = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_ticket_event' AND post_id = %d", $first ) );
}

echo $second;

Solution

You could try using a join between the two queries

$second = $wpdb->get_var( $wpdb->prepare("SELECT b.meta_value
FROM wp_postmeta a 
INNER JOIN wp_postmeta b ON a.post_id = b.post_id 
WHERE a.meta_key = '_ticket_order' AND a.meta_value = %d", $order_id ) );


Answered By - ScaisEdge

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.