如何为以下方案编写SQL查询

时间:2015-11-06 02:19:26

标签: sql

销售

order id : 1(primary key)
Billing address id -250
Shipping address id -285

地址表包含以下条目

id :250
Addressline1 : XXX
Addressline2 :YYY

id :285
Addressline1 : AAA
Addressline2 :BBB

如何编写查询以在单个查询中检索order id, billing address, shipping address

2 个答案:

答案 0 :(得分:1)

使用以下查询加入。以下是示例代码。

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

struct node
{
    int data;
    node* left;
    node* right;
};

node* root = NULL;

node* createLeaf(int data)
{
    node* n = new node;
    n->data = data;
    n->left = NULL;
    n->right = NULL;

    return n;
}
void addLeaf(int data)
{
    node* curr = root;


    //If tree is empty, create first node
    if(root == NULL)
    {
        root = createLeaf(data);

    }

    //Left(Less than)
    else if(data < curr->data)
    {
        //Check for curr->left
        if(curr->left != NULL)
        {
            addLeaf(data);
        }
        else //Adds node to left if null
        {
            curr->left = createLeaf(data);
        }
    }
    //Right(greater than)
    else if(data > curr->data)
    {
        //Check for curr->right
        if(curr->right != NULL)
        {
            addLeaf(data);
        }
        else //Adds node if right is Null
        {
            curr->right = createLeaf(data);
        }
    }
    else
    {
        cout << "The data " << data << " has already been received\n";
    }


}

void printTree(node* Ptr)
{


    if(root != NULL)
    {
        if(Ptr->left != NULL)
        {
            printTree(Ptr->left);
        }
        cout << Ptr->data << " ";
        if(Ptr->right != NULL)
        {
            printTree(Ptr->right);
        }
        cout << Ptr->data << " ";
    }
    else
    {
        cout << "The Tree is empty\n";
    }


}

int main()
{
    int data[4] = {1, 7, 5, 4};
    node* Ptr = root;


    for(int i = 0; i < 4; i++)
    {
        addLeaf(data[i]); 
    }

    printTree(Ptr);



    system("PAUSE");
    return 0;
}

答案 1 :(得分:0)

您可以多次加入address表格(使用outer join - 取决于潜在的null值):

select s.id, 
     billing.Addressline1,
     shipping.Addressline1
from sales s
    left join address billing on s.billingaddressid = billing.id
    left join address shipping  on s.shippingaddressid = shipping.id